Monday, June 18, 2012

How To Persist The State Of Data In Android

This is a sample activity which shows How to persist the state of the data i.e. if you save something on first launch it checks those setting when you relaunch the app.
Underlying Algorithm:
Basic description of algorithm in step by step form:
1.) Create a project StatePersistence.
2.) Put the following code snippet in res/layout/main.xml.
<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="" 

       <EditText android:id ="@+id/saved"
         <requestFocus />
3.) Activity persistent state is managed with the method getPreferences(int) inside the onPause() and onResume() lifecycle methods.
4.) Run the application.
Steps to Create:
1.) Open Eclipse. Use the New Project Wizard and select Android Project. Give the respective project name i.e. StatePersistence. Enter following information:
Project name: StatePersistence
Build Target: Google APIs
Application name: StatePersistence
Package name: com.sample.StatePersistence
Create Activity: StatePersistence
On Clicking Finish StatePersistence code structure is generated with the necessary Android Packages being imported along with StatePersistence class will look like following:
package com.sample.StatePersistence;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class StatePersistence extends Activity
    protected void onCreate(Bundle savedInstanceState) {
        editBox =(EditText)findViewById(;
    protected void onResume() {
        SharedPreferences prefs = getPreferences(0);
        String restoredText = prefs.getString("text"null);
        if (restoredText != null) {
            editBox.setText(restoredText, TextView.BufferType.EDITABLE);
            int selectionStart = prefs.getInt("selection-start"-1);
            int selectionEnd = prefs.getInt("selection-end"-1);
            if (selectionStart != -&& selectionEnd != -1) {
                editBox.setSelection(selectionStart, selectionEnd);
    protected void onPause() {
        SharedPreferences.Editor editor = getPreferences(0).edit();
        editor.putString("text", editBox.getText().toString());
        editor.putInt("selection-start", editBox.getSelectionStart());
        editor.putInt("selection-end", editBox.getSelectionEnd());
    private EditText editBox;
Output –The final output:

No comments:

Post a Comment