Activity Lifecycle

Entire Lifetime:  This is the lifetime between the first call to the onCreate() and the final call to onDestroy()method. We create all global resources such as screen layout, global variables etc in onCreate() and release all resources with onDestroy() call.


Visible Lifetime:  It is the lifetime of an Activity between onStart() and onStop() method calls. In this the Activity is visible to the user and he may or may not be able to interact with it. During the visible lifetime, an Activity maintains its state intact.


Foreground Lifetime:  Foreground lifetime starts with onResume() and ends with onPause() method calls. During this, the Activity is completely visible to the user and is on top of all other Activities so that user can interact with it.




Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity’s previously frozen state, if there was one. Always followed by onStart().


Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden. onStart() method is called before the Activity is being visible to the User. Activity is still not Active.


Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause(). With the onResume() method, the Activity become visible and Active for the user to interact with. The Activity will be at the top of the Activity stack at this point. Now the Activity is in running /active state and is able to receive user inputs.

Activities should override this method to perform tasks such as:

  • Ramping up frame rates (a common task in game building)
  • Starting animations
  • Listening for GPS updates
  • Display any relevant alerts or dialogs
  • Wire up external event handlers


Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().

  • In the Active state, onPause() method will be called when the system is about to resume another Activity on top of this one or when the user is about to navigate to some other other parts of the system. It is the last guaranteed call to a method before the Activity  can get killed by the system. That is, there’s a possibility that your activity may be killed by the system at the paused state without executing any further method calls. Therefore it is important to save the user interface configuration and critical data at this method.
  • By default, an Activity can remain in the paused state if:
  • The user has pressed the home button
  • Another activity or notification which is on top of it doesn’t completely obscures the visibility of underlying Activity.
  • The device goes to sleep.
  • There are three possibilities for an Activity under paused state:
  1. The user resumes the Activity by closing the new Activity or notification and the paused Activity gets Active/Running by calling onResume()
  2. It gets killed by the system under extremely low memory conditions. In this case there will be no further method calls before the destruction of the Activity and it needs to be re-run from the beginning by calling onCreate() and restoring the previous configuration from bundle object.

In all other cases it goes to stopped state by executing onStop() method. This is the default action when the user has pressed the back button, or a new activity which completely covers it resumes on top.

Activities should override this method if they need to:

  • Commit unsaved changes to persistent data
  • Destroy or clean up other objects consuming resources
  • Ramp down frame rates and pausing animations
  • Unregister external event handlers or notification handlers (i.e. those that are tied to a service). This must be done to prevent Activity memory leaks.
  • Likewise, if the Activity has displayed any dialogs or alerts, they must be cleaned up with the.Dismiss() method.


Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity’s process running after its onPause() method is called.

  • An Activity under stopped state also has three different scenarios to happen:
  1. System kills it to free resources. An activity under stopped sate is more likely to be killed by the system than one in the paused state. It needs to start the cycle again with onCreate().
  2. It get restarted by calling onRestart()onStart() and onResume() methods in the order if the user navigates back to the Activity again. In this case, the User Interface is intact and no need to be restored.
  3. onDestroy() method is called and the Activity is destroyed. This is the final method we can call before the Activity is destroyed. This occurs either because the Activity is finishing the operation or the system is temporarily destroying it to save space.


The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.


When the Activity first time loads the events are called as below:




When you click on Phone button the Activity goes to the background and the below events are called:



Exit the phone dialer and the below events will be called:




When you click the back button OR try to finish() the activity the events are called as below:




[Source :






Summary Notes : Storing and Retrieving data (SQLiteDatabase, Preference, File)

Application Preference (/data/data//shared_prefs/.xml)

Private Preference (Data sharing within activity)
Storing Data

SharedPreference sp = getPreferences(MODE_PRIVATE);
SharedPreference.Editor e = sp.edit();

Retrieving Data

SharedPreference sp = getPreferences(MODE_PRIVATE);
int score = sp.getInt(“Score”,null);
String name = sp.getString(“Name”,null);

Shared Preference (Data sharing between multiple activities of application)

Storing Data (In

SharedPreference sp = getSharedPreferences(“game”,0);
SharedPreference.Editor e = sp.edit();
Intent i = new Intent(getApplicationContext(), Activity2.class);

Retrieving Data (In

SharedPreference sp = getSharedPreferences(“game”,0);
int score = sp.getInt(“Score”,null);
String name = sp.getString(“Name”,null);

Reading and Writing data to file

Writing data to file

FileOutputStream fos;
String strFileContents = “Some text to write to the file.”;
fos = openFileOutput(“Filename.txt”, MODE_PRIVATE);

• or

FileOutputStream fOut = null;
OutputStreamWriter osw = null;
fOut = openFileOutput("test.txt", Context.MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write("Good morning!!! MCA-5");
catch(Exception e)
{ e.printStackTrace(System.err); }

Appending data to file

FileOutputStream fos;
String strFileContents = “More text to write to the file.”;
fos = openFileOutput(“Filename.txt”, MODE_APPEND);

Reading data to file

FileInputStream fIn = null;
InputStreamReader isr = null;
char[] b = newchar[1024];
String data = null;
fIn = openFileInput("test.txt");
isr = new InputStreamReader(fIn);;
data = new String(b);

TextView tv = (TextView) findViewById(;
catch(IOException e)
{ e.printStackTrace(System.err); }

Creating, deleting database and table with SQLite Database.

Creating and Deleteing Database:

SQLiteDatabase db;
db = openOrCreateDatabase(“mca.db”,SQLiteDatabase.CREATE_IF_NECESSARY,null);

Creating Table:

String s = “CREATE TABLE stud (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT);”;

Insert, Update and Delete operation with SQLite Database.

Insert Operation:

ContentValues cv = new ContentValues();
db.insert(“stud”, null,cv);


db.execSQL( “insert into tbl_authors(firstname, lastname) values (‘abc‘, ‘def‘ );” );

Update Operation:

ContentValues values = new ContentValues();
values.put(“firstname“, “aaa”);
db.update(“tbl_authors”, values, “lastname=?”, new String[] {“def“});


db.execSQL(“update tbl_authors set firstname=’aaa’ where lastname=’def‘;”);

Delete Operation:

db.delete(“tbl_authors”, “firstname=?”, new String[]{“aaa”});


db.execSQL(“delete from tbl_authors where firstname=’aaa'”);

Querying SQLite Database

SELECT * FROM tbl_books;

Cursor c = mDatabase.query(“tbl_books”,null,null,null,null,null,null);


Cursor c = db.rawQuery(“select * from tbl_books”);
SELECT * tbl_books WHERE id=9;
Cursor c = mDatabase.query(“tbl_books”, null, “id=?”, new String[]{“9”}, null, null, null);
SELECT title, id FROM tbl_books ORDER BY title ASC;
String asColumnsToReturn[] = { “title”, “id” };
String strSortOrder = “title ASC”;
Cursor c = mDatabase.query(“tbl_books”, asColumnsToReturn, null, null, null, null, strSortOrder);

Retrieving data from cursor

String s= c.getString(c.getColumnIndex(“fname”));
c.getCount(); (Count no. of rows)
c.getColumnCount(); (Count no. of columns)

Fetching data from multiple table

SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(“tbl_books, tbl_authors”);
String asColumnsToReturn[] = {
“tbl_books.authorid” };
String strSortOrder = “title ASC”;
Cursor c = queryBuilder.query(mDatabase, asColumnsToReturn,
null, null, null, null,strSortOrder);

• or

String sqlUnionExample = “SELECT title AS Name, ‘tbl_books’ AS OriginalTable from tbl_books WHERE Name LIKE ? UNION SELECT (firstname||’ ‘|| lastname) AS Name, ‘tbl_authors’ AS OriginalTable from tbl_authors WHERE Name LIKE ? ORDER BY Name ASC;”;
Cursor c = mDatabase.rawQuery(sqlUnionExample, new String[]{ “%ow%”, “%ow%”});

Working with transactions

// Insert some records, updated others, delete a few
// Do whatever you need to do as a unit, then commit it
} catch (Exception e) {
// Transaction failed. Failed! Do something here.
// It’s up to you.
} finally {

Summary Notes Chapter 10 Download

MediaStore Content Provider

Following code demonstrates retrieving audio files stored in sdcard and displaying list in listview. When user double clicks any of the song that music file will be played.

public class Test1Activity extends Activity 
/** Called when the activity is first created. */
ListView musiclist;
Cursor musiccursor;
int music_column_index;
int count;
MediaPlayer mMediaPlayer;

public void onCreate(Bundle savedInstanceState) {
private void init_phone_music_grid() {
	String[] proj = { 
		MediaStore.Video.Media.SIZE };
	musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
			proj, null, null, null);
	count = musiccursor.getCount();
	musiclist = (ListView) findViewById(;
	musiclist.setAdapter(new MusicAdapter(getApplicationContext()));

	mMediaPlayer = new MediaPlayer();

private OnItemClickListener musicgridlistener = new OnItemClickListener() {
	public void onItemClick(AdapterView parent, View v, int position,
				long id) {
	// TODO Auto-generated method stub
	music_column_index = musiccursor
	String filename = musiccursor.getString(music_column_index);
	try {
		if (mMediaPlayer.isPlaying()) {
	} catch (Exception e) {}


public class MusicAdapter extends BaseAdapter {
	private Context mContext;

	public MusicAdapter(Context c) {
		mContext = c;
	public int getCount() {
		return count;
	public Object getItem(int position) {
		return position;
	public long getItemId(int position) {
		return position;
	public View getView(int position, View convertView, ViewGroup parent) {
		TextView tv = new TextView(mContext.getApplicationContext());
		String id = null;
		if (convertView == null) {
		music_column_index = musiccursor
		id = musiccursor.getString(music_column_index);
		music_column_index = musiccursor
		id += " Size(KB):" + musiccursor.getString(music_column_index);
		} else
			tv = (TextView) convertView;
			return tv;

Contacts Content Provider

Following code demonstrates retrieving information such as no. of contacts using Contacts Content Provider.

Write the following code in onCreate() method.

Cursor oneContact = managedQuery( People.CONTENT_URI, null, null, null, null);
Log.d("TEMP2", "Count: " + oneContact.getCount());
Log.d("TEMP2", "column Count: " + oneContact.getColumnCount());