Thursday, February 26, 2015

Lesson 47 : android save data using SharedPreferences

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.putString("status", status);
 editor.putString("message", message);
 editor.apply();
SharedPreferences.Editor.apply() was introduced in Gingerbread in November, 2010 (after this answer was posted). Use it instead of commit() where possible since apply() is more efficient.

To retrieve data from shared preference
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);
  String status = prefs.getString("status","");
  String message = prefs.getString("message","");
}
source:
http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values

No comments:

Post a Comment