How to use Instance Save State in Android?

This Android Program demonstrates instance save state in android.

Here is source code of the program to demonstrate instance save state in android using java. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

MainActivity.java

package com.example.preferenceactivity;
 
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
public class MainActivity extends Activity {
 
    TextView text;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button but1 = (Button) findViewById(R.id.Prefsbutton);
        Button but2 = (Button) findViewById(R.id.GetPreferencesbutton);
        text = (TextView) findViewById(R.id.Prefstext);
        but1.setOnClickListener(new View.OnClickListener() {
 
            Intent in = new Intent("android.intent.action.Prefs");
 
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startActivity(in);
            }
        });
 
        but2.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                displaySharedPreferences();
            }
        });
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
    private void displaySharedPreferences() {
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
 
        String username = prefs.getString("username", null);
        String passw = prefs.getString("password", null);
        boolean checkBox = prefs.getBoolean("checkBox", false);
        String listPrefs = prefs.getString("listpref", "Default list prefs");
 
        StringBuilder builder = new StringBuilder();
        builder.append("Username: " + username + "\n");
        builder.append("Password: " + passw + "\n");
        builder.append("Keep me logged in: " + String.valueOf(checkBox) + "\n");
        builder.append("List preference: " + listPrefs);
 
        text.setText(builder.toString());
    }
}

Prefs.java

package com.example.preferenceactivity;
 
import android.os.Bundle;
import android.preference.PreferenceActivity;
 
public class Prefs extends PreferenceActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
 
        //addPreferencesFromResource(R.xml.pref);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefFragement()).commit();
    }
 
}

PrefesFragement.java

advertisement
advertisement
package com.example.preferenceactivity;
 
import android.os.Bundle;
import android.preference.PreferenceFragment;
 
public class PrefFragement extends PreferenceFragment{
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.pref);
    }
}

Activity_main.xml

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" 
    android:background="@android:color/darker_gray">
 
    <TextView
        android:id="@+id/Prefstext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/GetPreferencesbutton"
        android:layout_marginTop="102dp"
        android:text="Hello"
        android:textSize="20dp" 
        android:background="@android:color/white"
        android:textColor="@android:color/black"/>
 
    <Button
        android:id="@+id/Prefsbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Launch Preferences Screen"
        android:background="@android:color/white" />
 
    <Button
        android:id="@+id/GetPreferencesbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/Prefstext"
        android:layout_below="@+id/Prefsbutton"
        android:layout_marginTop="64dp"
        android:text="Display Shared Preferences"
        android:background="@android:color/white" />
 
</RelativeLayout>

pref.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" 
    android:title="....">
 <PreferenceCategory
   android:summary="Username and password information"
   android:title="Login information" >
  <EditTextPreference
     android:key="username"
     android:summary="Please enter your login username"
     android:title="Username" />
  <EditTextPreference
     android:key="password"
     android:summary="Enter your password"
     android:title="Password" />
 </PreferenceCategory>
 
 <PreferenceCategory
   android:summary="Username and password information"
   android:title="Settings" >
  <CheckBoxPreference
     android:key="checkBox"
     android:summary="On/Off"
     android:title="Keep me logged in" 
     android:defaultValue="false"/>
 
  <ListPreference
     android:entries="@array/Options"
     android:entryValues="@array/Values"
     android:key="listpref"
     android:summary="List preference example"
     android:title="List preference" />
 </PreferenceCategory>
</PreferenceScreen>

preferenceActivity1

advertisement

preferenceActivity2

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

advertisement
If you wish to look at all Tutorials, go to Java Android Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.