Shared Preferences:
Shared Preferences allow you to save and retrieve data in the form of key,value pair.
It can be used to save user login information inside app rather than calling server every time when user open app.
Data saved using shared preferences are persisted in app even after closing app. we can manually delete shared preferences or it will be deleted automatically when app is uninstalled.
syntax :
SharedPreferences sharedPreferences = getSharedPreferences("nameOfTheSharedPref",Context.MODE_PRIVATE);
Context.MODE_PRIVATE is used when you want your data only read by your app. this data is not shared with other app.
Below code shows how To create shared preferences
//define pref name
public static final String UserAccountInfo = "myPrefs";
//define keys
public static final String UserName = "nameOfUser";
public static final String UserMobileNumber = "mobileNumberOfUser";
//define values
String userName = "manoj";
String userMobileNumber = "1234567890";
//create an instance of shared preferences with a name called UserAccountInfo
//Context.MODE_PRIVATE is used when you want your data only read by your app.
SharedPreferences sharedPreferences = getSharedPreferences(UserAccountInfo,Context.MODE_PRIVATE);
//get instance of editor which is used to save data in key value pairs
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(UserName, userName);
editor.putString(UserMobileNumber, userMobileNumber);
//commit is important, which actually saves your preferences
editor.commit();
Below code shows how to delete/remove shared preferences
//get the shared preference which you want to delete
SharedPreferences sharedPreferences = getSharedPreferences(RegisterOtpScreenActivity.UserAccountInfo, Context.MODE_PRIVATE);
//remove preferences one by one
sharedPreferences.edit().remove(RegisterOtpScreenActivity.UserName).commit();
sharedPreferences.edit().remove(RegisterOtpScreenActivity.UserMobileNumber).commit();
//commit your changes
sharedPreferences.edit().clear().commit();
No comments:
Post a Comment