Friday, August 16, 2013

Shared Preference Example

Shared preference is used to store data globally and use it to anywhere in application. Two way we can use it.One is define global variable and other is shared preference.The main problem with global variable is data will be lost when user closes the application.To resolve this problem we can use shared preference.It maintains the data even user closes the app.


Initialization


Initialization of shared preference is given below.

SharedPreferences sp = this.getSharedPreferences("data",Activity.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();

Here,Editor is used to edit data of Shared Preference.

Store Data

Using Editor, you can store data into Shared Preference.We can use data types like boolean, string, int,float, long.Code is given below for all data types.

edit.putBoolean("enter_name",true);
edit.putString("enter_name","string_value");
edit.putInt("enter_name","int_value");
edit.putFloat("enter_name","float_value");
edit.putLong("enter_name","long_value");

edit.commit();    // Apply to store data.Don't forget to write it.

NOTE: edit.commit(); is the most important line.It is used to apply changes in shared preference.


Retrieve Data


You can retrieve Shared preference data through getString() method and so on.First of all you need to define Shared preference with same name.like:

 SharedPreferences sp = this.getSharedPreferences("data",Context.MODE_PRIVATE);

sp.getString("enter_name","default_string");
sp.getInt("enter_name",1);
sp.getBoolean("enter_name",true);
sp.getFloat("enter_name",null);
sp.getLong("enter_name",null);


Sample Code:

  • First Create 2 activities - 1. MainActivity.java    2. GetActivity.java.
  • MainActivity.java - Store data into Shared Preference.
  • GetActivity.java - Retrieve stored data.

MainActivity.java


public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sp = this.getSharedPreferences("abc",Activity.MODE_PRIVATE);
final SharedPreferences.Editor edit = sp.edit();
final EditText name = (EditText)findViewById(R.id.name);
final EditText pass = (EditText)findViewById(R.id.pass);
Button save = (Button) findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String sname =  name.getText().toString();
   String spass = pass.getText().toString();
  edit.putString("username", sname);
  edit.putString("password", spass);
  edit.commit();
}
});
Button retrive = (Button) findViewById(R.id.retrive);
retrive.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,GetActivity.class);
startActivity(intent);
}
});
}
}

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name:" />

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <EditText
        android:id="@+id/pass"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SAVE" />

    <Button
        android:id="@+id/retrive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Retrive Information" />

</LinearLayout>


GetActivity.java



public class GetActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get);
TextView usertv =(TextView)findViewById(R.id.usertext);
TextView passtv =(TextView)findViewById(R.id.passtext);
SharedPreferences sp = this.getSharedPreferences("abc",Context.MODE_PRIVATE);

 usertv.setText(sp.getString("username","" ));
passtv.setText(sp.getString("password", ""));
}
}


activity_get.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".GetActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Get Data" />

    <TextView
        android:id="@+id/usertext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="Username" />

    <TextView
        android:id="@+id/passtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="Password" />

</LinearLayout>



Download Full Source Code:  Here



1 comment: