android - 如果从最近的 Activity android 中删除应用程序,则会清除 SharedPreferences

标签 android sharedpreferences

我在我的项目中通过 MODE_PRIVATE 使用 SharedPreferences,当我从最近的 Activity 列表中清除该应用程序并再次打开该应用程序时,我的所有偏好数据都被清除。

我正在使用这个类(class)来设置和获取偏好。

public class Preferences {

private Context _context;
private SharedPreferences _preferences;
private Editor _editor; 
private String prefName =   "pref";

//=====
public Preferences(Context context){

    _context = context;
    _preferences = this._context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
    _editor = this._preferences.edit();
}

//=====
public Preferences commit(){
    _editor.commit();
    return this;
}

//===== 
public Preferences set(String key, String value){

    _editor.putString(key, value);
    return this;
}

//=====
public String get(String key){      
    return _preferences.getString(key, "");
}

//===== 
public Preferences set(String key, int value){

    _editor.putInt(key, value);
    return this;
}

//=====
public int getInt(String key){      
    return _preferences.getInt(key, 0);
}

//===== 
public Preferences setBoolean(String key, boolean value){

    _editor.putBoolean(key, value);
    return this;
}

//=====
public void removeKey(String key){
    _editor.remove(key);
}

//=====
public boolean getBoolean(String key){      
    return _preferences.getBoolean(key, false);
}

}

谁能帮我...?

最佳答案

像这样改变你的设置方法

public Preferences set(String key, int value){

    _editor.putInt(key, value);
    _editor.commit();
    return this;
}

你不需要单独的 commit() 到独立的方法中。

祝你好运

关于android - 如果从最近的 Activity android 中删除应用程序,则会清除 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26311701/

相关文章:

android - 无法恢复 Activity - SharedPreferences

list - Flutter:使用定界符从列表创建 map

Android Junit 测试与普通 Junit 测试

java - Android:如何动态获取应用程序的总大小?

android - HAXM 未安装

android - Android MediaPlayer同时提供3个音频

android - SharedPreference 更改未反射(reflect)在我的墙纸服务中

android - 如何将图片保存到文件?

android从java设置默认首选项

java - 将数据从 EditText 传递到另一个 Activity 中的 TextView 并使用共享首选项保存它