private static final String KEY_HOROSCOPE = "HOROSCOPE";
private String mHoroscope;
鉴于上面的代码,如何持久保存mHoroscope
的值?保存时,如何加载mHoroscope
的持久存储值?
答案 0 :(得分:0)
您可以使用文件来保存变量的值
从文件中读取:
File f = new File(Address);
FileReader r = new FileReader(f);
BufferedReader b = new BufferedReader(r);
String out = "";
String k="";
while( (out=b.readLine()) != null) {
k+=out;
}
b.close();
所以字符串k就是答案
写入文件:
File file = new File(Address);
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(YourString);
bw.close();
答案 1 :(得分:0)
您可以使用SharedPreferences
保存值。
private SharedPreferences mPreferences = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// initialize the SharedPreferences, 'this' is a context
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
// get the value for key (suppose the value type is boolean)
private boolean getBoolean(String key, boolean defValue) {
return mPreferences.getBoolean(key, defValue);
}
// save the value for key (suppose the value type is boolean)
private void putBoolean(String key, boolean value) {
mPreferences.edit().putBoolean(key, value).apply();
}
答案 2 :(得分:0)
关闭应用时,将SharedPreference用于持久数据 创建一个全局变量
SharedPreferences mSharedPreference;
初始化onCreate
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
存储值:
Editor e = mSharedPreferences.edit();
e.putString(KEY_HOROSCOPE, value);
e.commit();
要追溯:
String horoscope = mSharedPreferences.getString(KEY_HOROSCOPE, "");
如果您只想在关闭应用时清除它,请使用Bundle。