To use shared Prefs, you need to save the value to SharedPreferences
:
// Update your preferences when the chronometer is paused, so put this in your OnPause
SharedPreferences prefs = getSharedPreferences("mySharedPrefsFilename", Context.MODE_PRIVATE);
// Don't forget to call commit() when changing preferences.
prefs.edit().putLong("chronoValue", chrono.getValue()).commit();
//In your OnResume, you need to call the value back
SharedPreferences prefs = getSharedPreferences("mySharedPrefsFilename", Context.MODE_PRIVATE);
chornostore = prefs.getLong("chronoValue", 0); // 0 is default
That should get you on the right track.
Edit:
So the deal with SharedPrefs is that you can store and access data from anywhere in your application - the catch is that the data has to be Float
, String
, Int
, Boolean
, Long
or a String
array (set). Since you're trying to save a Long
value from the Chronometer, you need to save that value via putLong
Getting the Data:
Step 1: initialize a SharedPreferences instance using getSharedPreferences:
// Context.MODE_PRIVATE means only this application has access to the files.
// You can set any name for the file, and the instance. I used "SharedPrefsFileName" and prefs respectively.
SharedPreferences prefs = getSharedPreferences("SharedPrefsFileName", Context.MODE_PRIVATE);
Step 2: Call the data from your SharedPreferences instance:
// The second argument is the value to return if there is no "chronoValue" data. In this case, it will return "0"
chornostore = prefs.getLong("chronoValue", 0);
Storing the Data:
Step 1: Initialize a SharedPreferences.Editor
//Use the same SharedPreferences instance and then instantiate an editor for storing:
SharedPreferences prefs = getSharedPreferences("SharedPrefsFileName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Step 2: Store the Data:
//Use the same "chronoValue" Name for the Name-Value pair that is accepted as the arguments:
editor.putLong("chronoValue", chronostore);
Step 3: Commit the changes to SharedPreferences:
editor.commit();
And that's all there is to it.
Depending on your usage, you might find it helpful to store/call the values in your application's onPause
and onResume
methods.
If you need more help, read through the helpful usage guide here:
http://developer.android.com/guide/topics/data/data-storage.html#pref
or the documentation here:
http://developer.android.com/reference/android/content/SharedPreferences.html