How to use SharedPreferences in Android to store, fetch and edit values [closed] How to use SharedPreferences in Android to store, fetch and edit values [closed] android android

How to use SharedPreferences in Android to store, fetch and edit values [closed]


To obtain shared preferences, use the following methodIn your activity:

SharedPreferences prefs = this.getSharedPreferences(      "com.example.app", Context.MODE_PRIVATE);

To read preferences:

String dateTimeKey = "com.example.app.datetime";// use a default value using new Date()long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

To edit and save preferences

Date dt = getSomeDate();prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

Edit==>

I noticed, it is important to write difference between commit() and apply() here as well.

commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.

apply() was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.More detail is here.


To store values in shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);SharedPreferences.Editor editor = preferences.edit();editor.putString("Name","Harneet");editor.apply();

To retrieve values from shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);String name = preferences.getString("Name", "");if(!name.equalsIgnoreCase("")){    name = name + "  Sethi";  /* Edit the value here*/}


To edit data from sharedpreference

 SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putString("text", mSaved.getText().toString()); editor.putInt("selection-start", mSaved.getSelectionStart()); editor.putInt("selection-end", mSaved.getSelectionEnd()); editor.apply();

To retrieve data from sharedpreference

SharedPreferences prefs = getPreferences(MODE_PRIVATE); String restoredText = prefs.getString("text", null);if (restoredText != null) {  //mSaved.setText(restoredText, TextView.BufferType.EDITABLE);  int selectionStart = prefs.getInt("selection-start", -1);  int selectionEnd = prefs.getInt("selection-end", -1);  /*if (selectionStart != -1 && selectionEnd != -1)  {     mSaved.setSelection(selectionStart, selectionEnd);  }*/}

Edit

I took this snippet from API Demo sample. It had an EditText box there . In this context it is not required.I am commenting the same .