Saturday, 15 September 2012

Android Shared Preference Example

Android provide SharedPrefrences object to help you save simple(small) amount of data and it is accessable with in your application.

Using SharedPrefrences  class you can save and retrive .This information saved as .xml in your System(Mobile).

SharedPrefrences can accept any primitive data
Character (character, char);
Integer (integer, int, short, long, byte) with a variety of precisions
Floating-point number (float, double, real, double precision)

Steps to use Shared Prefrences in Android

Store Data in SharedPrefrence


Step 1: Create SharedPrefences Object

In Android thier is 2 methods for getting SharedPrefrences.

One is getSharedPreferences(<name of the File>,<mode>)

This method will be used if you have multiple prefrences files identified by name in your application.and in that file all data will be stored.

Example:

Private SharedPrefrences prefrenceobj =getSharedPrefrences("androidsurya",MODE_PRIVATE);

Second one is  getPreferences(<mode>)

mode parameter     is an Operating mode. Use MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.

Example:
Private SharedPrefrences prefrenceobj =getSharedPrefrences(MODE_PRIVATE);

Step 2: Create editor object using prefrenceobj which is allready created at Step 1.
SharedPrefrences.Editor editor=prefrenceobj.edit();
The Editor class allows you to save key/value pairs to prefrences file by exposing some methods such as the following
putString()
putBoolean()
putLong()
putInt()
putFloat()

Example:
editor.putString("Firstname","surya");
Here Firstname is a key and surya is a value.

Step 3: Call commit() on prefrenceobj which is allready created at Step 1
prefrenceobj .commit();

commit() will save all values in xml.

Get Data from SharedPrefrences file

To get values which are allready stored early we use getXXX() method.
Here XXX nothing but a any methods like
getString("KEY")
getFloat("KEY")
getInt("KEY") etc....

Example:

prefrenceobj .getString("Firstname");

The shared preferences file is saved as an XML file in the /data/data/<package_name>/shared_prefs folder /"yourprividedfile".xml

Its content is shown here (formatted for clarity):
<?xml version=’1.0’ encoding=’utf-8’ standalone=’yes’ ?>
<map>
<string name=”Firstname”>surya</string>
</map>


Clearing / Deleting Data

We can delete data from SharedPrefrence using remove("KEY") for  particular value
If you want to delete all the data, call clear() on SharedPrefrence object...


Now we can see one Example Android Project Using SharedPrefrences Store data and Retrive data(Firstname)

UI Layout(shared_prefrence.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/firstname"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your First Name" />

    <Button
        android:id="@+id/save_fname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save First Name" />

    <Button
        android:id="@+id/retrive_fname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Retrive First name" />

</LinearLayout>

Android Activity class(SharedPrefrenceActivity.java)


package com.androidsurya.sharedprefrences;

import android.os.Bundle;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SharedPrefrenceActivity extends Activity {

    EditText firstname;
    TextView textSavedMem1, textSavedMem2;
    Button save_fname, retrive_fname;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shared_prefrence);
        firstname = (EditText) findViewById(R.id.firstname);
        save_fname = (Button) findViewById(R.id.save_fname);
        retrive_fname = (Button) findViewById(R.id.retrive_fname);
        save_fname.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SavePreferences("FirstName", firstname.getText().toString());
                Toast.makeText(getApplicationContext(),
                        "Saved in SharedPrefrences", Toast.LENGTH_LONG).show();
            }
        });
        retrive_fname.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
                String firstname = sharedPreferences.getString("FirstName", "");
                Toast.makeText(
                        getApplicationContext(),
                        "Retrived FirstName from SharedPrefrences           "
                                + firstname, Toast.LENGTH_LONG).show();
            }
        });
    }

    private void SavePreferences(String key, String value) {
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

}

Register Activity in AndroidManifest file

 <activity
            android:name="com.androidsurya.sharedprefrences.SharedPrefrenceActivity"
            android:label="@string/app_name" >

Output Screenshot









 

Now you can see the SharedPrefrence file

Open File Explorer and view below path
In File Explorer  /data/data/com.androidsurya.sharedprefrences/shared_prefs /SharedPrefrenceActivity.xml

Screenshot:






No comments:

Post a Comment

Android SQLite Database Viewer or Debuging with Stetho

Every Android Developer uses SQLite Database to store data into the Android Application data. But to view the data in SQLite have a lot of...