tags:

views:

63

answers:

2

I want to store a time value and need to retrieve and edit it. Can somebody guide me here with a sample code/project please? Thankyou

+2  A: 

To edit data from sharedpreference

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

To retrieve data from shared preference

SharedPreferences prefs = getPreferences(0); 
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 Edit Text box there... In this context it is not required.I am commenting the same

Rahul
+1, but use getPreferences(MODE_PRIVATE); instead of getPreferences(0); for readability.
Key
What is mSaved here? I need to save 2 string values.
Maxood
A: 

To obtain shared preferences, use the following method In 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 long = prefs.getLong(dateTimeKey, new Date().getTime()); 

To edit and save preferences

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

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

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
naikus
So the next time user runs my app, the stored value is there already and i can fetch it...right?
Maxood
Yes you can fetch it.
naikus