Google+ android tutorials

Translate

Friday, 19 December 2014

SharedPreferences Example in Android




                                                                                            
In this Post we are going to see how to use Android sharedpreferences. You can permanently store your preferences using sharedpreferences with the form of  key and  value pair.
Android Storage can be done in many ways and one of the way is shared preferences.

Some important way of storing the data in android:
  • Shared Preferences: Primitive data storage (Boolean, Strings, ints etc.).
  • Internal Storage: Device memory storage.
  • External Storage: Store public data on storage media, like SD cards.
  • SQLite Database.

In   sharedpreferences we talk about permanent storage about the application. That means that if you uninstall the application, all your data will be lost, so this is application specific. If you want to store few amount of data then you can go for Shared Preferences rather than going for SQLite and all.In that case Shared Preferences are useful. Many time it is use for session management in android.


Session are useful when you want to store user data globally through out the application. This can be done in two ways. One is storing them in a global variables and second is storing the data in shared preferences. The problem with storing data in global variable is data will be lost once user closes the application, but storing the data in shared preferences will be persistent even though user closes the application.

What is sharedpreferences in android :
Shared Preferences is an API from Android SDK to store and retrieve application preferences. Shared Preferences are simply sets of data values that stored persistently. Persistently which mean data you stored in the Shared Preferences are still exist even if you stop the application or turn off the device. SharedPreferences available at the Activity level or shared across all Activity in application package.

What is Editor in android :
Editor is a interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply().
How to initialize the  sharedpreference in android : 
Android shared preferences can be fetched using getSharedPreferences() method in Application.You also need an editor to edit and save the changes in shared preferences. The below code can be used to get application shared preferences.

SharedPreferences pref = getApplicationContext().getSharedPreferences("Pref", 0);  
Editor editor = pref.edit();

How to store the data in sharedpreferences :
You can save data into shared preferences using editor. All the primitive data types like booleans, floats, ints, longs, and strings are supported by this. You have to call the editor.commit() in order to make save changes in shared preferences.


editor.putBoolean("key_name", true); // For storing boolean like - true/false

editor.putString("key_name", "string value"); // For storing string

editor.putInt("key_name", "int value"); // For Storing integer

editor.putFloat("key_name", "float value"); // For Storing float

editor.putLong("key_name", "long value"); // For Storing long

editor.commit(); // In order to make changes

How to retrieve the data in sharedpreferences :
You can retrieve the data from saved preferences by calling getString() (For string) method. Remember this method should be called on Shared Preferences not on Editor.

// If value is not present return second param value - In this case null

pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean


How to delete or clear the data in sharedpreferences :



If you want to delete from shared preferences you can call remove(“key name”) to delete that particular value.

editor.remove("key name");  // it will delete the corresponding item of key in sharedpreference
  editor.commit(); // make commit in order to make changes in sharedpreference

If you want to delete all the data, call clear();

editor.clear();       // delete all the data
editor.commit();   //
make commit in order to make changes in sharedpreference

Lets takes a simple example to show the core concept behind this :-


  • Create a new project in Eclipse File > New > Android Application Project and fill the required details.
  • Here we have five total five activity and five xml file called layout files. 
  • You can copy paste all activities and xml files in your project one by one carefully and also can download the complete working project sample from download link.
Here is the SplashActivity.java file : This is a launcher activity, working as a splash screen. 

public class SplashActivity extends Activity {

    public static String str_login_test;

    public static SharedPreferences sh;
    public static Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.splash);

        // here initializing the shared preference
        sh = getSharedPreferences("myprefe", 0);
        editor = sh.edit();

        // check here if user is login or not
        str_login_test = sh.getString("loginTest", null);

        if (getIntent().getBooleanExtra("EXIT", false)) {
            finish();
            return;
        }

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                /*
                 * if user login test is true on oncreate then redirect the user
                 * to result page
                 */

                if (str_login_test != null
                        && !str_login_test.toString().trim().equals("")) {
                    Intent send = new Intent(getApplicationContext(),
                            LogoutActivity.class);
                    startActivity(send);
                }
                /*
                 * if user login test is false on oncreate then redirect the
                 * user to login & registration page
                 */
                else {

                    Intent send = new Intent(getApplicationContext(),
                            Login_and_Registration.class);
                    startActivity(send);

                }
            }

        }, 3000);

    }


}


Here is the Login_and_Registration.java : This is the activity to show the button for  login and registration


public class Login_and_Registration extends Activity implements OnClickListener {

    Button login, register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_registration);

        login = (Button) findViewById(R.id.btn_login);
        register = (Button) findViewById(R.id.btn_register);

        login.setOnClickListener(this);
        register.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {
        case R.id.btn_login:

            // on login button click send to login activity

            Intent login = new Intent(getApplicationContext(), Login.class);

            startActivity(login);

            break;

        // on register button click send to register activity

        default:
            Intent registeration = new Intent(getApplicationContext(),
                    Registration.class);

            startActivity(registeration);
            break;
        }

    }

    // on back key press exit the application.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(Login_and_Registration.this,
                    SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("EXIT", true);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

}



Here is the Registration.java : This is the activity to make the registration.

public class Registration extends Activity implements OnClickListener {

    Button register;
    String url;

    String str_Name, str_Password, str_RePassword, str_Email, str_Mobile,
            random;

    EditText edt_Name, edt_Password, edt_RePassword, edt_Email, edt_Mobile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.registration);

        register = (Button) findViewById(R.id.btn_register);
        edt_Name = (EditText) findViewById(R.id.edt_Rname);
        edt_Password = (EditText) findViewById(R.id.edt_Rpassword);
        edt_RePassword = (EditText) findViewById(R.id.edt_RRepassword);
        edt_Mobile = (EditText) findViewById(R.id.edt_Rmobile);
        edt_Email = (EditText) findViewById(R.id.edt_email);

        register.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        str_Name = edt_Name.getText().toString();
        str_Password = edt_Password.getText().toString();
        str_RePassword = edt_RePassword.getText().toString();
        str_Mobile = edt_Mobile.getText().toString();
        str_Email = edt_Email.getText().toString();

        if (str_Name.length() == 0 & str_Password.length() == 0
                & str_RePassword.length() == 0 & str_Mobile.length() == 0) {
            Toast.makeText(getApplicationContext(),
                    "All fields are mandatory to fill", Toast.LENGTH_LONG)
                    .show();
        } else if (str_Name.length() == 0) {
            Toast.makeText(getApplicationContext(), "Please enter your Name",
                    Toast.LENGTH_LONG).show();
        } else if (str_Password.length() == 0) {
            Toast.makeText(getApplicationContext(),
                    "Please enter your Password", Toast.LENGTH_LONG).show();
        } else if (str_RePassword.length() == 0) {
            Toast.makeText(getApplicationContext(),
                    "Please Re-enter your Password", Toast.LENGTH_LONG).show();
        }

        else if (str_Email.length() == 0) {
            Toast.makeText(getApplicationContext(),
                    "Please enter your Email Id", Toast.LENGTH_LONG).show();
        }

        else if (str_Password.contains(str_RePassword) != str_RePassword
                .contains(str_Password)) {
            Toast.makeText(getApplicationContext(),
                    "Confirm Password does not match", Toast.LENGTH_LONG)
                    .show();
        } else if (str_Mobile.length() == 0) {

            Toast.makeText(getApplicationContext(),
                    "Please enter your mobile number", Toast.LENGTH_LONG)
                    .show();

        }

        else {
            SplashActivity.editor.putString("name", str_Name);
            SplashActivity.editor.putString("password", str_RePassword);
            SplashActivity.editor.putString("email", str_Email);
            SplashActivity.editor.putString("mobile", str_Mobile);

            SplashActivity.editor.commit();

            Intent sendtoLogin = new Intent(getApplicationContext(),
                    Login_and_Registration.class);

            Toast.makeText(getApplicationContext(),
                    "You have successfully registered", Toast.LENGTH_LONG)
                    .show();

            startActivity(sendtoLogin);

        }

    }

    // on back key press exit the application.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(Registration.this, SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("EXIT", true);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

}


Here is the Login.java : This is the activity to make the login.


public class Login extends Activity implements OnClickListener {

    String str_UserName, str_Password, str_getID, str_getPass;

    EditText edt_UName, edt_Password;

    Button login;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        /* fetching the data from shared preference in order to make user login */
        /* data are saved in application through SplashActivity */
        /* only name and password is sufficient to make login */

        str_getID = SplashActivity.sh.getString("name", null);
        str_getPass = SplashActivity.sh.getString("password", null);
        login = (Button) findViewById(R.id.btn_login);
        edt_UName = (EditText) findViewById(R.id.edt_userName);
        edt_Password = (EditText) findViewById(R.id.edt_password);

        login.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        str_UserName = edt_UName.getText().toString();
        str_Password = edt_Password.getText().toString();

        /* make edittext condition for empty, input etc match */

        if (str_UserName.length() == 0 & str_Password.length() == 0) {
            Toast.makeText(getApplicationContext(),
                    "Please enter your login User Name and Password",
                    Toast.LENGTH_LONG).show();
        } else if (str_UserName.length() == 0) {
            Toast.makeText(getApplicationContext(),
                    "Please enter your User Name", Toast.LENGTH_LONG).show();
        } else if (str_Password.length() == 0) {
            Toast.makeText(getApplicationContext(),
                    "Please enter your Password", Toast.LENGTH_LONG).show();
        }

        else if (str_getID.matches("") && str_getPass.matches("")) {
            Toast.makeText(getApplicationContext(),
                    "Details does not belongs to any account",
                    Toast.LENGTH_LONG).show();
        }

        else if (!(str_UserName.matches(str_getID))) {
            Toast.makeText(getApplicationContext(),
                    "Either login/password is incorrect", Toast.LENGTH_LONG)
                    .show();
        }

        else if (!(str_getPass.matches(str_Password))) {
            Toast.makeText(getApplicationContext(),
                    "Either login/password is incorrect", Toast.LENGTH_LONG)
                    .show();
        }

        else if ((str_getID.matches(str_UserName))
                && (str_getPass.matches(str_Password))) {

            /*
             * dont forget to commit after doing the operation with shared
             * preference
             */
            /* without commit data will not saved to shared preference */
            SplashActivity.editor.putString("loginTest", "true");
            SplashActivity.editor.commit();

            Toast.makeText(getApplicationContext(),
                    "You have successfuly login", Toast.LENGTH_LONG).show();

            Intent sendToLogout = new Intent(getApplicationContext(),
                    LogoutActivity.class);

            startActivity(sendToLogout);
        }

    }

    // on back key press exit the application.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(Login.this, SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("EXIT", true);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }
}



Here is the LogoutActivity.java : This is the activity to make the logout.

 public class LogoutActivity extends Activity implements OnClickListener {

    String str_getName, str_getPassword, str_getEmail, str_getMobile;

    TextView profile;

    Button logout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.logout);

        /*
         * fetching the all data corresponding to each key from shared
         * preference in order to show the user profile
         */

        str_getName = SplashActivity.sh.getString("name", null);
        str_getPassword = SplashActivity.sh.getString("password", null);
        str_getEmail = SplashActivity.sh.getString("email", null);
        str_getMobile = SplashActivity.sh.getString("mobile", null);

        profile = (TextView) findViewById(R.id.txt_profile);
        logout = (Button) findViewById(R.id.logout);
        logout.setOnClickListener(this);

        /* set fetch data to textview, textview show the user complete profile */

        profile.setText("Name : " + str_getName + "\n" + "\n" + "Password : "
                + str_getPassword + "\n" + "\n" + "Email : " + str_getEmail
                + "\n" + "\n" + "Mobile : " + str_getMobile);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        /*
         * logout button click does not delete the shared preference all data
         * but it only delete the user login test key, you can do the login
         * again with same credentials. In order to delete the complete data
         * call editor.clear(); followed by editor.commit(); you can edit your
         * complete profile by doing registration once again, it will overwrite
         * your previous data.
         */
        Toast.makeText(getApplicationContext(), "You have successfully logout",
                Toast.LENGTH_LONG).show();
        SplashActivity.editor.remove("loginTest");

        SplashActivity.editor.commit();

        Intent sendToLoginandRegistration = new Intent(getApplicationContext(),
                Login.class);

        startActivity(sendToLoginandRegistration);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(LogoutActivity.this,
                    SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("EXIT", true);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }
}


 Here is the splash.xml :

<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:background="@drawable/splash" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="170dp"
        android:text="Welcome To"
        android:textColor="#569B1A"
        android:textSize="15sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="200dp"
        android:autoLink="web"
        android:text="http://androidtutorialsrkt.blogspot.in/"
        android:textColor="#569B1A"
        android:textSize="15sp"
        android:textStyle="bold" />

</RelativeLayout> 


Here is the login_registration.xml :

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

    <Button
        android:id="@+id/btn_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="116dp"
        android:background="@drawable/btn_login_reg_design"
        android:ems="10"
        android:padding="10dp"
        android:text="Login"
        android:textColor="#ffff00"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_login"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="23dp"
        android:background="@drawable/btn_login_reg_design"
        android:ems="10"
        android:padding="10dp"
        android:text="Register"
        android:textColor="#ffff00"
        android:textStyle="bold" />

</RelativeLayout> 



Here is the registration.xml :

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true" >

    <LinearLayout
        android:id="@+id/parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFE9B1"
        android:orientation="vertical" >

        <EditText
            android:id="@+id/edt_Rname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="80dp"
            android:background="@drawable/edt_design"
            android:ems="12"
            android:hint="User Name"
            android:padding="10dp" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/edt_Rpassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:background="@drawable/edt_design"
            android:ems="12"
            android:hint="Password"
            android:inputType="textPassword"
            android:padding="10dp" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/edt_RRepassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:background="@drawable/edt_design"
            android:ems="12"
            android:hint="Confirm Password"
            android:inputType="textPassword"
            android:padding="10dp" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/edt_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:background="@drawable/edt_design"
            android:ems="12"
            android:hint="Email Id"
            android:inputType="textEmailAddress"
            android:padding="10dp" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/edt_Rmobile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:background="@drawable/edt_design"
            android:ems="12"
            android:hint="Mobile No."
            android:inputType="number"
            android:padding="10dp" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/btn_register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="40dp"
            android:background="@drawable/btn_login_reg_design"
            android:ems="10"
            android:padding="10dp"
            android:text="Register"
            android:textColor="#ffff00"
            android:textStyle="bold" />
    </LinearLayout>

</ScrollView>





Here is the login.xml :

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true" >

    <LinearLayout
        android:id="@+id/parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFE9B1"
        android:gravity="center"
        android:orientation="vertical" >

        <EditText
            android:id="@+id/edt_userName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/edt_design"
            android:ems="12"
            android:hint="User Name"
            android:padding="10dp" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/edt_password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:background="@drawable/edt_design"
            android:ems="12"
            android:hint="Password"
            android:inputType="textPassword"
            android:padding="10dp" />

        <Button
            android:id="@+id/btn_login"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:background="@drawable/btn_login_reg_design"
            android:ems="10"
            android:padding="10dp"
            android:text="Login"
            android:textColor="#ffff00"
            android:textStyle="bold" />
    </LinearLayout>

</ScrollView>



Here is the logout.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt_welcome"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="5dp"
        android:autoLink="web"
        android:text="Welcome to androidtutorialsrkt.blogspot.in"
        android:textColor="#569B1A"
        android:textSize="15sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/contactUs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txt_welcome"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="5dp"
        android:text="Contact Us at : robi.tomar72@gmail.com and call us at +918586875317 for help"
        android:textColor="#569B1A"
        android:textSize="15sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txt_profile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="150dp"
        android:text="profile"
        android:textColor="#0000FF"
        android:textSize="15sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/logout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="40dp"
        android:background="@drawable/btn_login_reg_design"
        android:ems="10"
        android:padding="10dp"
        android:text="Logout"
        android:textColor="#ffff00"
        android:textStyle="bold" />

</RelativeLayout>


Here is the ouput screen :








Download the complete project here.

You can also download a sample project here.