Showing posts with label Tips and Tricks. Show all posts
Showing posts with label Tips and Tricks. Show all posts

Tuesday, July 12, 2011

AlarmManager and NotificationManager sample code

This is not a complete tutorial on how to use AlarmManager and NotificationManager, but a simple sample.

The scenario is I want to have an alarm set to certain time. When it goes off, it show notification icon on status bar. When click on the notification, it will start an activity.

1. Create the BroadcastReceiver

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager mNM;
        mNM = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, "Test Alarm",
        System.currentTimeMillis());
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, TestActivity.class), 0);
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(context, context.getText(R.string.alarm_service_label), "This is a Test Alarm", contentIntent);
        // Send the notification.
        // We use a layout id because it is a unique number. We use it later to cancel.
        mNM.notify(R.string.alarm_service_label, notification);
    }
}

2. Add Receiver to Manifest.xml

<receiver android:process=":remote" android:name="AlarmReceiver"></receiver>

3. Set the alarm

public class AlarmService {
    private Context context;
    private PendingIntent mAlarmSender;
    public AlarmService(Context context) {
        this.context = context;
        mAlarmSender = PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class), 0);
    }

    public void startAlarm(){
        //Set the alarm to 10 seconds from now
        Calendar c = Calendar.getInstance();
        c.add(Calendar.SECOND, 10);
        long firstTime = c.getTimeInMillis();
        // Schedule the alarm!
        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, firstTime, mAlarmSender);
    }
}

How to use and customize tab(image, font)?

1. Create tabs


TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, TaskActivity.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("task").setIndicator("Task", null).setContent(intent);
tabHost.addTab(spec); // Do the same for the other tabs
intent = new Intent().setClass(this, CalendarActivity.class);
spec = tabHost.newTabSpec("calendar").setIndicator("Calendar", null).setContent(intent);
tabHost.addTab(spec);

2. Customize tabs


TabHost tabHost = getTabHost();
LinearLayout linearLayout = (LinearLayout) tabHost.getChildAt(0);
TabWidget tw = (TabWidget) linearLayout .getChildAt(0);
RelativeLayoutfirstTabLayout = (RelativeLayout) tw.getChildAt(0);
//First tab
TextViewtabHeader = (TextView) firstTabLayout .getChildAt(1);
tabHeader .setTextSize(18); //Change text size
tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 36;
//Change first tab header height
firstTabLayout.setBackgroundResource(R.drawable.group_background_overdue);
tabHeader.setText("Tab page 1");


How to sort array list?

Sort by simple type property

1. Implement the Comparable interface


public class Item implements Comparable<Item> {

}

2. Implement the compareTo method.


@Override
public int compareTo(Item another) {
//Compare the name
return this.name.compareTo(another.name);
}

3. Call sort


List<Item> items = ..
items.sort();

Sort by user defined property

1. Create a new class


import java.util.Comparator;
public class ItemCompareByLocation implements Comparator<Item>{
@Override
public int compare(Item arg0, Item arg1) {
return arg0.getLocation().compareTo(arg1.getLocation());
}
}

2. Call sort


Collections.sort(items, new ItemCompareByLocation());

How to use Style

Create style.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="DetailTextView" parent="@android:style/TextAppearance">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textSize">14sp</item>
<item name="android:textStyle">bold</item>
</style>
<style name="DateTimeButton" parent="@android:style/Widget.Button">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:gravity">left|center_vertical</item>
<item name="android:textSize">19sp</item>
</style>
</resources>

Use it in layout


<TextView android:id="@+id/TextView01" android:text="What" style="@style/DetailTextView" />

How to show toast?

Simple toast:


Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();

Customized toast:


LayoutInflater inflater;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.detail_toast,
(ViewGroup)arg0.findViewById(R.id.toast_layout_root));
TextView taskTextView = (TextView)
layout.findViewById(R.id.taskTextView);
taskTextView.setText(task.getName());
TextView detailTextView = (TextView)
layout.findViewById(R.id.detailTextView);
detailTextView.setText(sb.toString());
Toast toast = new Toast(context.getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

Thursday, August 19, 2010

Miscellaneous Tips

How to stretch a control?

Set Layout_weight to greater than 0

image

image

 

Issue with Check box in a list view

When I use anything other than textview in a listview, the context menu stop working. Now to have a check box in a list view, I have to use CheckedTextView. But the text in CheckedTextView appears on the left side of the checkbox. I don’t know how to change it, so I use a CheckedTextView with no text and a TextView.

 

Show checkbox in CheckedTextView

<CheckedTextView android:id="@+id/categoryCheckedTextView"
android:layout_width="wrap_content"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:layout_height="wrap_content"
android:clickable="true">
</CheckedTextView>

Display simple MessageBox in Android


AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Packing List");
alertDialog.setMessage("Could not find the file.");
alertDialog.show();

 

Change emulator orientation

Use KEYPAD_7 or KEYPAD_9 on you desktop. You need to turn off your Num Lock.


Dynamically change the background color

To dynamically change the background color, use myView.setBackgroundResource(R.color.my_color) instead myView.setBackgroundColor(R.color.my_color)

 

How to align text in text view?

When trying to align the text to the right in text , set the “layout_gravity” to right doesn’t work. Need to set “gravity” to right.

Monday, August 9, 2010

ClassNotFound exception when unmarshalling

The following code is the serialization part of the Category class in PackingList project. Since the category has an arraylist of items, I have to put it in Bundle. To de-serialize it, I need to retrieve items from the Bundle. To do that, I was using Bundle d = in.readBundle(). However, I received “ClassNotFound exception when unmarshalling”. I have to pass in the ClassLoader so it knows it’s for the Item.

 

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(category);
Bundle b = new Bundle();
b.putParcelableArrayList("items", items);
dest.writeBundle(b);

}

public static final Parcelable.Creator<Category> CREATOR =
new Parcelable.Creator<Category>() {
public Category createFromParcel(Parcel in) {
Category category = new Category();
category.category = in.readString();
Bundle b = in.readBundle(Item.class.getClassLoader());
category.items = b.getParcelableArrayList("items");

return category;
}

@Override
public Category[] newArray(int size) {
return new Category[size];
}
};

How to display progress dialog?

private ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
……

dialog = ProgressDialog.show(this, "",
"Loading Calendar and Tasks. Please wait...", true);

……
CalendarThread calendarThread = new CalendarThread();
calendarThread.start();

}

private class CalendarThread extends Thread {

@Override
public void run() {
//Long running process
……

handler.sendEmptyMessage(0);
}

private Handler handler = new Handler() {

@Override
public void handleMessage(Message msg) {
//Process after the long running process
……
dialog.dismiss();
}
};
}

Monday, February 8, 2010

Creating custom dialog in Android

This blog shows you an example on how to create custom dialog. For more information on creating different kind of dialogs, please visit http://developer.android.com/guide/topics/ui/dialogs.html
1. Create layout for the dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10sp">
<EditText android:text=""
android:id="@+id/categoryEditText"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:singleLine="true">
</EditText>
</LinearLayout>



2. Override onCreateDialog in the Activity
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CATEGORY_DETAIL:
LayoutInflater li = LayoutInflater.from(this);
View categoryDetailView = li.inflate(R.layout.category_detail, null);

AlertDialog.Builder categoryDetailBuilder = new AlertDialog.Builder(this);
categoryDetailBuilder.setTitle("Edit Category");
categoryDetailBuilder.setView(categoryDetailView);
AlertDialog categoryDetail = categoryDetailBuilder.create();

categoryDetail.setButton("OK", new OnClickListener(){

@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog categoryDetail = (AlertDialog)dialog;
EditText et = (EditText)categoryDetail.findViewById(R.id.categoryEditText);
if (categories.get(selectedIndex)!=null){
//... some code
}
});

categoryDetail.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}});

return categoryDetail;
default:
break;
}
return null;
}


3. Override onPrepareDialog to dynamically set default value before the dialog is open
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case CATEGORY_DETAIL:
AlertDialog categoryDetail = (AlertDialog)dialog;
EditText et = (EditText)categoryDetail.findViewById(R.id.categoryEditText);
et.setText(defaultValue);
break;
default:
break;
}
}


4. Call showDialog to display the dialog
static final private int CATEGORY_DETAIL = 1;
//... some code
showDialog(CATEGORY_DETAIL);


Monday, February 1, 2010

Passing a list of objects between Activities

In Android, you can use Bundle to pass data between activities. There are many functions to pass Integer, String, etc. To pass an object, you will need to implement Parcelable interface and override some functions to serialize/de-serialize the object. Here is an example:
public class Category implements Parcelable {
private String category;
private ArrayList<Item> items;

public String getCategory() {
return category;
}

public void setCategory(String category) {
this.category = category;
}

public ArrayList<Item> getItems() {
return items;
}

public void setItems(ArrayList<Item> items) {
this.items = items;
}

public Category(){

}

public Category(String _category){
category = _category;
}

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(category);
Bundle b = new Bundle();
b.putParcelableArrayList("items", items);
dest.writeBundle(b);

}

public static final Parcelable.Creator<Category> CREATOR = 
new Parcelable.Creator<Category>() { 
public Category createFromParcel(Parcel in) { 
Category category = new Category();
category.category = in.readString();
Bundle b = in.readBundle(Item.class.getClassLoader());        
category.items = b.getParcelableArrayList("items");

return category;
}

@Override
public Category[] newArray(int size) {
return new Category[size];
}
};
}


To pass an arraylist  of Category to another activity,
intent i = new Intent(_av.getContext(), ItemList.class);
Bundle b = new Bundle();
b.putParcelableArrayList("categories", categories);
b.putInt("index", _index);
i.putExtras(b);
startActivityForResult(i, ITEM_LIST);

To retrieve the data,
Bundle b = this.getIntent().getExtras();

ArrayList<Category> cats = b.getParcelableArrayList("categories");
int index = b.getInt("index");

How to add MessageBox in Android?

Simple message box with no buttons
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Packing List");
alertDialog.setMessage("Could not find the file.");
alertDialog.show();

Message box with buttons
AlertDialog deleteAlert = new AlertDialog.Builder(this).create();
deleteAlert.setTitle("Delete List");
deleteAlert.setMessage("Are you sure you want to delete this list?");
deleteAlert.setButton("Yes", new OnClickListener(){

@Override
public void onClick(DialogInterface dialog, int which) {               
//...
}
});
deleteAlert.setButton2("No", new OnClickListener(){

@Override
public void onClick(DialogInterface dialog, int which) {
//...
}
});
deleteAlert.show();

Thursday, January 14, 2010

Read, Write and Parse XML file in Android

1. Read and Parse Xml file
The sample XML file looks like the following:
<packingList>
<category name="test">
</category>
<packingList>


The following code shows you how to read and parse the file
ArrayList<Category> categories;
XmlPullParser parser = Xml.newPullParser();
try {
FileInputStream fIn = openFileInput(FILE_NAME);
InputStreamReader isr = new InputStreamReader(fIn);

// auto-detect the encoding from the stream
parser.setInput(isr);
int eventType = parser.getEventType();
Category currentCategory = null;
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done){
String name = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("packingList")){
categories = new ArrayList<Category>();
} else if (categories != null){
if (name.equalsIgnoreCase("category"))
currentCategory = new Category(parser.getAttributeValue(0));
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("category") &&
currentCategory != null){
categories.add(0, currentCategory);
} else if (name.equalsIgnoreCase("packingList")){
done = true;
}
break;
}
eventType = parser.next();
}
} catch (FileNotFoundException e) {
// TODO
} catch (IOException e) {
// TODO
} catch (Exception e){
// TODO
}


2. Write to file
 
try {
FileOutputStream fOut = openFileOutput(FILE_NAME, MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
String fileContent = …; //build file content
osw.write(fileContent );
osw.flush();
osw.close();

} catch (FileNotFoundException e) {

}