Monday 26 August 2013

How to use SharedPreference to store information in key-value pair in Android.


This tutorial explains how to store small amount of information using SharedPreferences APIs, and how to retrieve their values.


Here we take an example of login form. When user enter their login credentials, and checked the checkbox (i.e. Remember), the credentials store in the application, and when user opens that application again, user not need to enter their login information again. To store information we write:


SharedPreferences preferences = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();

Here we set Context.MODE_PRIVATE, so the file is accessible by only your application.

If you want to reset your preferences .

SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();


No comments:

Post a Comment