State Persistence

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"?-->
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:freezesText="true">

 

 

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.java. StatePersistence class will look like following:

 

package com.sample.StatePersistence;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

public class StatePersistence extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editBox =(EditText)findViewById(R.id.saved);
}
protected void onResume() {
super.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 != -1 && selectionEnd != -1) {
editBox.setSelection(selectionStart, selectionEnd);
}
}
}

protected void onPause() {
super.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());
editor.commit();
}

private EditText editBox;
}

 

 

Output –The final output:

Leave a Comment:

15 comments
E3D3 says May 29, 2011

Just what I was looking for & nice page. Thanks.

Reply
Andy says June 6, 2011

Nice, it worked ! But how do you save several edit text boxes? I have five I need to save on one page..

Reply
Andy says June 13, 2011

Nice, but how do I save two edit boxes?

Reply
Sushant says June 13, 2011

Try this

[code lang="java"]

public class StatePersistence extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editBox =(EditText)findViewById(R.id.saved);
editBox2 =(EditText)findViewById(R.id.saved1);
}
protected void onResume() {
super.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 != -1 && selectionEnd != -1)
{
editBox.setSelection(selectionStart, selectionEnd);
}
SharedPreferences prefs2 = getPreferences(1);
String restoredText2 = prefs2.getString("text2", null);
if (restoredText2 != null)
{
editBox2.setText(restoredText2, TextView.BufferType.EDITABLE);

int selectionStart2 = prefs2.getInt("selection-start2", -1);
int selectionEnd2 = prefs2.getInt("selection-end2", -1);
if (selectionStart2 != -1 && selectionEnd2 != -1)
{
editBox2.setSelection(selectionStart2, selectionEnd2);
}
}
}
}

protected void onPause() {
super.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());
editor.commit();

SharedPreferences.Editor editor2 = getPreferences(1).edit();
editor2.putString("text2", editBox2.getText().toString());
editor2.putInt("selection-start2", editBox2.getSelectionStart());
editor2.putInt("selection-end2", editBox2.getSelectionEnd());
editor2.commit();
}

private EditText editBox;
private EditText editBox2;
}

[/code]

Reply
Andy says June 13, 2011

It is exactly what I was looking for ! Thank you very much ! You solved my problem .

Reply
Andy says June 13, 2011

Sushant, I don’t want to be annoying and give impression I want people do work for me. But if you get a chance, maybe you could advice how to also save state of check boxes that I am intending to put next to the editText boxes.

Reply
    Sushant says June 14, 2011

    You can try:

    [code lang="java"]

    @Override
    public void onPause() {
    super.onPause();
    save(mCheckBox.isChecked());
    }
    @Override
    public void onResume() {
    super.onResume();
    mCheckBox.setChecked(load());
    }
    private void save(final boolean isChecked) {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("check", isChecked);
    editor.commit();
    }
    private boolean load() {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    return sharedPreferences.getBoolean("check", false);
    }
    [/code]

    Reply
seb says July 18, 2011

very nice tutorial! i need to save a string and resume it after application is killed
i’ll definetly try this method! thanks

Reply
Matthew says August 14, 2011

Sushant, could you help me out and show me how to save three edittext boxes on one page?

Reply
Matthew says August 14, 2011

Never mind, I figured it out

Reply
Matthew says August 14, 2011

Do you know how to save what has been selected in a spinner? I want the selected item to be displayed on the spinner when I relaunch the activity, but I do not need it to do anything.

Reply
iwyz80 says December 5, 2011

This tutorial was really helpful but am still havig some little problem.I plan to use sharedPreferences to check for an already entered password so that when the application starts again I can request to change that password to a knew one by entering the last old password all in an edittext

Reply
Anthonio says December 5, 2011

This was a very nice turorial.I have been trying to apply this method to my application but am having some kind of difficulty.
I am making a password application that can allow the user to change the old password(Just like keying in the security code of mobile fone(eg Galaxy S2)) which allows the user to enter an old password for the first time only and when the user wants to change this password he/she must confirm by entering the old password.
Please I need help with this. I have tried all i could using preferences but no success. Any help will be greatly appreciated.

Reply
Anthonio says December 5, 2011

Hello,This was a very nice turorial.I have been trying to apply this method to my application but am having some kind of difficulty.
I am making a password application that can allow the user to change the old password(Just like keying in the security code of mobile fone(eg Galaxy S2)) which allows the user to enter an old password for the first time only and when the user wants to change this password he/she must confirm by entering the old password.
Please I need help with this. I have tried all i could using preferences but no success. Any help will be greatly appreciated.

Reply
SJD says January 24, 2012

Very good Tutorial!!!
My question, however, is how do you save multiple check boxes?

Reply
Add Your Reply