1.

I want to store some text value like UserName and need to retrieve and edit it. How can I use SharedPreferences to do this?

Answer»

In Android, we have many ways to store user data. SharedPreference is a CLASS that allows us to save and retrieve user data in the form of Key and Values. If you kill your application still data will be saved in the shared preference.  It will store data in an XML file. For using shared preference we need to create an INSTANCE of the getSharedPreferences method. This method is taking two parameters:

For WRITING data in the sharedpreferences file we need to follow below steps:

  • Call edit() to get a SharedPreferences.Editor
  • Add values with methods such as putInt() and putString
  • Call commit() to save values.
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit(); editor.putString("name", "ABC"); editor.commit();

To read values use such methods as getString() and getInt() of SharedPreferences instance.

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String restoredText = prefs.getString("text", null); if (restoredText != null) {  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.  }


Discussion

No Comment Found

Related InterviewSolutions