问题
I want to save data with sharedpreference.This data come from another Activity.
回答1:
Write to Shared Preferences
To write to a shared preferences file, create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass the keys and values you want to write with methods such as putInt() and putString(). Then call commit() to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read from Shared Preferences
To retrieve values from a shared preferences file, call methods such as getInt() and getString(), providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
回答2:
You can save key value pairs using sharedpreferences. For example, to store an int, you can do something like this:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("your_key", 50);
editor.commit();
You can later retrieve the value using:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
long score = sharedPref.getInt("your_key", defaultValue);
回答3:
You can save value using this method:
public void saveDataPreference(Context context,
String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
And using this method you can get value from SharedPreferences:
public String getPreferences(Context context, String prefKey) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPreferences.getString(prefKey, "");
}
Here prefKey is the key that you used to saved the specific value. If you want to save data , then just use it:
String yourData="Some Data";
String yourKey="YOUR_KEY";
saveDataPreference(getActivity(),yourData);
and get that data using this way:
String prefdata=getPreferences(getActivity(),yourKey);
thanks.
回答4:
use key,value in SharedPreferences
来源:https://stackoverflow.com/questions/31889816/how-to-save-data-from-come-another-activity