SharedPreferences

SharedPreferences is a way to store small amount of data to disk in the form of key-value pairs.
Three terms is commonly used; key,value and defValue
Key: A non-null String identifying the parameter. It can contain whitespace or non-printables. Don’t localize it just used default language.
Value: The storing value against Key.
defValue: All the get functions take a default value, which is returned if the given key is not present in the SharedPreferences.

SharedPreferences sharedPreferences;
SharedPreferences.Editor prefEditor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
////////Initialize Prefrence///////////////
sharedPreferences = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);
prefEditor = sharedPreferences.edit();
///////////////Saved Data//////////////////
prefEditor.putBoolean("check", true); //Save boolean data
prefEditor.putInt("count", 1); //Save Integer data
prefEditor.putString("msg", "My messsages"); //Save Stringdata
prefEditor.commit();
///////////////Get Data//////////////////
boolean check= sharedPreferences.getBoolean(check, true);
int phoneNumber = sharedPreferences.getInt(count, 0);
String messsages= sharedPreferences.getString(msg, "No data");
 }
}

Comments