How to save data from come another Activity [closed]

淺唱寂寞╮ 提交于 2019-12-25 19:45:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!