Monday, April 26, 2010

ExpandableListActivity in Android

I want to use expandablelist activity, when I want to show two lists in a single screen like a main list and a sub-list. For example, a list of countries are there(Main list) and I want to show the main cities(sub-list) of theses countries. In that case, expandable list activity will be very useful. This is just one use of expandable list. Like that it can use for hundreds of purposes.

The complete code is,

public class CountryStateList extends ExpandableListActivity {

private static final String NAME = "NAME";
private static final String IS_EVEN = "IS_EVEN";
private ExpandableListAdapter mAdapter;
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
InputStream is;
boolean addState = true;
boolean addCountry;
HashMap<String, String> countryMap = new HashMap<String, String>();
HashMap<String, String> stateMap = new HashMap<String, String>();
int count = 0;
int count1 = -1;
int count2 = 0;
List<String> stateCount = new ArrayList<String>();

public void onCreate(Bundle savedInstanceState) {
// Reading data from text file to inout stream
is = this.getResources().openRawResource(R.raw.countrystate);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line = "";
while ((line = reader.readLine()) != null) {
String[] strings = line.split("-");
String ctry = strings[0].trim();
String st = strings[1].trim();
* loading country and state to two separate hash tables
if (countryMap.containsValue(ctry)) {
addCountry = false;
if (!addState) {
stateMap.put("state" + count1 + count2, st);
} else {
addCountry = !addCountry;
//adding no. of states for a country to a list
stateCount.add("" + count2);
if (addCountry) {
count2 = 0;
countryMap.put("country" + count, ctry);
stateMap.put("state" + count1 + count2, st);
addState = false;
} catch (Exception e) {
//re-arranging the state count list
stateCount.add("" + count2);
for (int i = 0; i < countryMap.size(); i++) {
Map<String, String> curGroupMap = new HashMap<String, String>();
String ctry = countryMap.get("country" + i);
curGroupMap.put(NAME, ctry);
curGroupMap.put(IS_EVEN, "Country " + i);
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
int k = Integer.parseInt(stateCount.get(i));
for (int j = 0; j < k; j++) {
Map<String, String> curChildMap = new HashMap<String, String>();
curChildMap.put(NAME, stateMap.get("state" + i + j));
curChildMap.put(IS_EVEN, "State " + j);

// Set up our adapter
mAdapter = new SimpleExpandableListAdapter(this, groupData,
android.R.layout.simple_expandable_list_item_1, new String[] {
NAME, IS_EVEN }, new int[] {, }, childData,
android.R.layout.simple_expandable_list_item_2, new String[] {
NAME, IS_EVEN }, new int[] {, });

For getting data about country and cities, I used a text file


India - Delhi
India - Haryana
India - Uttar Pradesh
India - Rajastan
India - Jammu Kashmir
India - Orissa
India - West Bengal
India - Manipur
India - Tripura
India - AndraPradesh
India - Gujarat
India - Maharashtra
India - Madhya Pradesh
India - Karnataka
India - Tamil nadu
India - Kerala
India - Goa
Sri Lanka - Colombo
Sri Lanka - Kandalama
Sri Lanka - Gampola
Sri Lanka - Haragama
West Indies - Jamaica
West Indies - Barbados
West Indies - Virgin Islands
West Indies - Trinidad
West Indies - Bermuda
Australia - Melbourne
Australia - Perth
Australia - Sydney
Australia - Adelaide
Australia - Gulginni
Pakistan - Islamabad
Pakistan - Peshawar
Pakistan - Lahore
Pakistan - Karachi
Bangladesh - Dhaka
Bangladesh - Khulna
Bangladesh - Silet
South Africa - Johannesburg
South Africa - Cape Town

The screenshots are,

AlarmManager and Notification in Android

In this, I am going to explain AlarmManager and Notification. For Notifying Users in Android, we can use mainly 3 methods as,


The full picture of this can seen here

AlarmManager, we can use in two ways, as

-To start some action, if a particular event happens,
-To do some particular actions in every time interval.

As specified in Android developer site, we will use AlarmManager, when we need to do some actions, even if our application is not running. For normal timing operations use handlers.

For using AlaramManager, first we need to declare the BroadcastReceiver in Manifest file as,

<receiver android:name=".TimeAlarm" />
We need to get the object of the AlarmManager using getSystemService(), then define an intent with parameters as the current context and the BoradcastReceiver class(TimeAlarm). Then define a pendingIntent, we will get the object of it using PendingIntent.getBroadcast(). Now we can call the set() of AlarmManager for doing some action for only once. For repetitive action we have to call setRepeating() of the AlarmManager.

In TimeAlarm, to show to user that our AlarmManager is working we will show a notification in status bar. For that first get the object of NotificationManager using, getSystemService(). Create an object of pendingIntent using PendingIntent.getActivity(). Then create an object of the notification and pass it to the notification manager object.

I created a sample program and the complete source code is,

public class CustomAlarm extends Activity {

 AlarmManager am;

 public void onCreate(Bundle savedInstanceState) {
  am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

 public void setOneTimeAlarm() {
  Intent intent = new Intent(this, TimeAlarm.class);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
  am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);

 public void setRepeatingAlarm() {
  Intent intent = new Intent(this, TimeAlarm.class);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
  am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (5 * 1000), pendingIntent);

public class TimeAlarm extends BroadcastReceiver {

 NotificationManager nm;

 public void onReceive(Context context, Intent intent) {
  nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  CharSequence from = "Nithin";
  CharSequence message = "Crazy About Android...";
  PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
  Notification notif = new Notification(R.drawable.icon, "Crazy About Android...", System.currentTimeMillis());
  notif.setLatestEventInfo(context, from, message, contentIntent);
  nm.notify(1, notif);

The screenshots are,

AsyncTask in Android

AsyncTask allows us to do proper background operations without creating threads and handlers. AsyncTask will run in the background thread and whose results we can pass to the UI thread. To implement AsyncTask, what we need to do is, create a class which extends AsyncTask and need to override some methods in it like doInBackground(), onPostExecute(), onProgressUpdate().

Sample program is,

private class BackgroundTask extends AsyncTask {

protected Void doInBackground(Void... params) {
protected void onPostExecute(Void result) {
protected void onProgressUpdate(Integer... progress) {


We can call AsyncTask using, new BackgroundTask().execute();

Fetching IMEI number in Android

We can fetch the IMEI number of android phones using,

TelephonyManager mTelephonyMgr = (TelephonyManager)
String imei = mTelephonyMgr.getDeviceId();

ContentProvider in Android

I already told about the built-in content-providers in Android, in one of my tutorial

In this, I am creating a new custom content provider. For this, first we will declare the content provider in Manifest file as,

<provider android:name="Provider" android:authorities="simple.provider"/>

So,Provider is my content provider name. Created a class called Provider which extends ContentProvider. The CONTENT_URI, which I am going to use is, "content://simple.provider/mytable"

The complete source code is,

public class Provider extends ContentProvider {

public static final String AUTHORITY = "simple.provider";
// public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
// + "/table1");
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/mytable");
public static final String CONTENT_TYPE = "";
public static final String CONTENT_ITEM_TYPE = "";
public static final String DATABASE_NAME = "MyDatabase";
public static final String TABLE_NAME = "mytable";
public static final int DATABASE_VERSION = 2;
public static final int TABLE = 1;
public static final int ROW_ID = 2;
public static final UriMatcher sUriMatcher;
public static final String FIRSTNAME = "first_name";
public static final String LASTNAME = "last_name";
private SQLiteDatabase sqlitedb;

static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(AUTHORITY, "mytable", TABLE);
sUriMatcher.addURI(AUTHORITY, "mytable/#", ROW_ID);

class DatabaseHelper extends SQLiteOpenHelper {

public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);

public void onCreate(SQLiteDatabase db) {
+ "last_name VARCHAR);");

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mytable;");

// creating database
public boolean onCreate() {
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
sqlitedb = databaseHelper.getWritableDatabase();
return (sqlitedb == null) ? false : true;

public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;

public String getType(Uri uri) {
switch (sUriMatcher.match(uri)) {
case TABLE:
case ROW_ID:
throw new IllegalArgumentException("Unknown URI : " + uri);

// inserting data into database
public Uri insert(Uri uri, ContentValues values) {
long row_id = sqlitedb.insert(TABLE_NAME, "", values);
try {
if (row_id > 0) {
Uri uri1 = ContentUris.withAppendedId(CONTENT_URI, row_id);
getContext().getContentResolver().notifyChange(uri1, null);
return uri1;
} catch (Exception e) {
Log.e("Fail to insert the row into database",
"Fail to insert the row into database");
return null;

// accessing records from database
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
if (sUriMatcher.match(uri) == ROW_ID)
sqlBuilder.appendWhere("id" + " = " + uri.getPathSegments().get(1));
Cursor c = sqlBuilder.query(sqlitedb, projection, selection,
selectionArgs, null, null, sortOrder);
// ---register to watch a content URI for changes---
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;

public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
return 0;

To accessing the ContentProvider, use ContentResolver. We can get the object using getContentResolver()

The complete source code for this is,

public class SimpleProvider extends Activity {

public void onCreate(Bundle savedInstanceState) {

ContentValues values = new ContentValues();
values.put(Provider.FIRSTNAME, "Nithin");
values.put(Provider.LASTNAME, "Warrier");
getContentResolver().insert(Provider.CONTENT_URI, values);

ContentValues values1 = new ContentValues();
values1.put(Provider.FIRSTNAME, "Guna");
values1.put(Provider.LASTNAME, "Boss");
getContentResolver().insert(Provider.CONTENT_URI, values1);

Cursor c = managedQuery(Provider.CONTENT_URI, null, null, null, null);
int count = 1;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
Log.i("Row " + count + " "
+ c.getString(c.getColumnIndex(Provider.FIRSTNAME)), c

ViewStub in Android

In this, I just going to show how to use ViewStub in Android. Once again, I am telling this is just a very basic tutorial for ViewStub.

The complete code is,

public class SampleViewStub extends Activity {

ViewStub stub;
boolean click = true;

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
findViewById( OnClickListener() {

public void onClick(View v) {
if (click) {
stub = (ViewStub) findViewById(;
click = false;


<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Showing ViewStub" />

<Button android:id="@+id/openstub" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Open ViewStub" />

<ViewStub android:id="@+id/stub1" android:inflatedId="@+id/showlayout"
android:layout="@layout/layout1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_gravity="bottom"/>


<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android=""
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TextView android:id="@+id/label_import" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Textview from Viewstub" />

<Button android:id="@+id/button_cancel" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:minWidth="100dip"
android:text="Next" />


The screenshots are,

Sunday, April 25, 2010

Swipe Action and ViewFlipper in Android

Last tutorial I talked about ViewFlipper, in this I am just extending the functonality of ViewFlipper with swipe action. ViewFlipper is mainly used to animate views. I have two or three views added to the ViewFlipper and using the API showNext() and showPrevious(), we can show the next and previous view in the ViewFlipper. At the time of switching, we can create some animation and it looks great.

Foe switching between views, we can either use time interval or through user interaction. Last tutorial I used button for switching between Views. In this tutorial I am going to use swipe action for switching views.

class MyGestureDetector extends SimpleOnGestureListener {

  private static final int SWIPE_MIN_DISTANCE = 120;
  private static final int SWIPE_MAX_OFF_PATH = 250;
  private static final int SWIPE_THRESHOLD_VELOCITY = 200;

  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
   System.out.println(" in onFling() :: ");
   if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
    return false;
   if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
     && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
   } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
     && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
   return super.onFling(e1, e2, velocityX, velocityY);

SWIPE_MIN_DISTANCE is used to make sure, the action is a swipe. Swipe will be valid only if we swipe upto this SWIPE_MIN_DISTANCE.
SWIPE_MAX_OFF_PATH is to make sure the swipe is almost in a straight line.

Then create an object of GestureDetector and pass our MyGestureDetector as an argument to its constructor.

GestureDetector gestureDetector;
gestureDetector = new GestureDetector(new MyGestureDetector());

Then create a OnTouchListener for flipper and attach the object of GestureDetector to it.

flipper.setOnTouchListener(new OnTouchListener() {

   public boolean onTouch(View v, MotionEvent event) {
    if (gestureDetector.onTouchEvent(event)) {
     return false;
    } else {
     return true;

Thursday, April 22, 2010

Changing layout height dynamically

We can change the layout height dynamically to say, x by using

getLayoutParams().height= x;
requestLayout(); or invalidate();

ViewFlipper in Android

ViewFlipper is used to do animation when switching between views. There are lot of options for doing animations between views like ViewAnimator, LayoutAnimationController, applying animation to the view itself. But I feel ViewFlipper is the better option for doing animation for switching views.

In this I am controlling the switching between views using user interaction(Button click). We can set duration also for switching between views.

The complete code for showing ViewFlipper is,

public class ShowFlipper extends Activity {

ViewFlipper flipper;
Button button1;
Button button2;
LinearLayout l1;
LinearLayout l2;
TextView tv1, tv2, tv3, tv4, tv5, tv6;

public void onCreate(Bundle savedInstanceState) {
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,

flipper = new ViewFlipper(this);
l1 = new LinearLayout(this);
l2 = new LinearLayout(this);
button1 = new Button(this);
button2 = new Button(this);
button1.setText("Button 1");
button2.setText("Button 2");

tv1 = new TextView(this);
tv2 = new TextView(this);
tv3 = new TextView(this);
tv4 = new TextView(this);
tv5 = new TextView(this);
tv6 = new TextView(this);
tv1.setText("text view 1");
tv2.setText("text view 2");
tv3.setText("text view 3");
tv4.setText("text view 4");
tv5.setText("text view 5");
tv6.setText("text view 6");
l1.addView(tv1, params);
l1.addView(tv2, params);
l1.addView(tv3, params);
l1.addView(button1, params);
l2.addView(tv4, params);
l2.addView(tv5, params);
l2.addView(tv6, params);
l2.addView(button2, params);


button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

private Animation inFromRightAnimation() {
Animation inFromRight = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, +1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
inFromRight.setInterpolator(new AccelerateInterpolator());
return inFromRight;

private Animation outToLeftAnimation() {
Animation outtoLeft = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, -1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
outtoLeft.setInterpolator(new AccelerateInterpolator());
return outtoLeft;

private Animation inFromLeftAnimation() {
Animation inFromLeft = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, -1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
inFromLeft.setInterpolator(new AccelerateInterpolator());
return inFromLeft;

private Animation outToRightAnimation() {
Animation outtoRight = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, +1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
outtoRight.setInterpolator(new AccelerateInterpolator());
return outtoRight;

You can download the full source code from here

Tuesday, April 20, 2010

PopupWindow in Android

This tutorial is about PopUpWindow in Android. Actually popupwindow came to my mind, when I need a dialog, to position at the bottom of the screen. PopupWindow is like "" only, but the main difference is in this we can position, where it need to be displayed. Not only that, now using the setElevation() (from API level 21) we can use it as a context menu. For example when long click on an view, pop up a window using PopupWindow and give the options as a list

In popupwindow also we can add a layout, much like in dialog.

The complete code is,
public class ShowPopUp extends Activity {

 PopupWindow popUp;
 LinearLayout layout;
 TextView tv;
 LayoutParams params;
 LinearLayout mainLayout;
 Button but;
 boolean click = true;

 public void onCreate(Bundle savedInstanceState) {
  popUp = new PopupWindow(this);
  layout = new LinearLayout(this);
  mainLayout = new LinearLayout(this);
  tv = new TextView(this);
  but = new Button(this);
  but.setText("Click Me");
  but.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    if (click) {
     popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
     popUp.update(50, 50, 300, 80);
     click = false;
    } else {
     click = true;

  params = new LayoutParams(LayoutParams.WRAP_CONTENT,
  tv.setText("Hi this is a sample text for popup window");
  layout.addView(tv, params);
  // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
  mainLayout.addView(but, params);

Here, I am creating all the layout in java itself. I am not using XML for creating layout. As my current project need all the layouts in Java, I am used to create now the layout in Java itself.

The another point I want to mention is, if we put,

popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
popUp.update(50, 50, 300, 80);

this code in onCreate() wont work. So I put the code in listener of the button.

Dream Big and Work Smart To Make It a Reality !!!

Saturday, April 10, 2010

Activity Launch Mode in Android

Android activity launchMode

4 modes...


The default mode is "standard".

The modes fall into two groups. standard and singleTop comes in one side and singleTask and singleInstance comes in another side.

The main difference between standard and singleTop is in standard, every time a new intent for standard activity, a new instance is created. In case of singleTop too, a new instance is created but an instance of the activity is already in top of the stack, it wont create a new instance.

Actually, the issue comes , when we download an application from a server and launch it and open it from there itself. After launching the application, press home button. Then click the all programs and select the icon of the application from home screen. Then another activity will be created in the case of standard, but in singleTop , no new instance will be created.

The "singleTask" and "singleInstance" modes also differ from each other in only one respect: A "singleTask" activity allows other activities to be part of its task. It's at the root of the activity stack, but other activities (necessarily "standard" and "singleTop" activities) can be launched into the same task. A "singleInstance" activity, on the other hand, permits no other activities to be part of its task. It's the only activity in the task. If it starts another activity, that activity is assigned to a different task — as if FLAG_ACTIVITY_NEW_TASK was in the intent.

Friday, April 9, 2010

Failed to initialize Monitor Thread in Android

When I am working on Eclipse suddenly, I got this error

Failed to initialize Monitor Thread: Unable to establish loopback connection android

I have no idea, why this error occurs. After some mind grilling, I came to know, its because of the settings in firewall, so reset the firewall and my eclipse and adb work normally.