SharedPreferences getInt()一直返回0

时间:2017-04-17 22:38:30

标签: java android sharedpreferences

我无法理解为什么我的代码无效。出于某种原因,似乎没有找到关键的“业力”,然后当调试器到达此行时,它将this.karmaPoints设置为0:“this.karmaPoints = settings.getInt(”karma“,0);”

public void incrementKarmaPoints(Context context) {
    SharedPreferences settings;
    Editor editor;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();
    editor.putInt("karma", this.karmaPoints++);
    editor.commit();
}

public int getKarmaPoints(Context context) {
    SharedPreferences settings;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    this.karmaPoints = settings.getInt("karma", 0);
    return karmaPoints;
}

任何建议都会很棒!

3 个答案:

答案 0 :(得分:2)

我猜this.karmaPoints一开始就是0。当您尝试保存this.karmaPoints++时,这意味着您将值0传递给编辑器并仅在之后递增值。 例如,尝试将this.karmaPoints的值设置为10。 并将this.karmaPoints++更改为++this.karmaPoints

答案 1 :(得分:2)

嗯,它实际上很简单,就像我在评论中说的那样,在Post-Increment中,值首先在表达式中使用,然后递增。

public void incrementKarmaPoints(Context context) {
    SharedPreferences settings;
    Editor editor;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();
    this.karmaPoints+=1; // or ++this.karmaPoints
    editor.putInt("karma",this.karmaPoints );
    editor.apply();
}

答案 2 :(得分:0)

尝试以下方法;使用默认首选项

public static void storeValueInSharedPrefs(Context context, String key){
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

    SharedPreferences.Editor editor = preferences.edit();

    //as pointed out below by the other guys; increment before storing 
    //the value in preferences
    int karma = karma + 1;
    editor.putInt(key, karma);

    editor.apply();
}

然后像这样获取或读取它:

public static int getValueFromSharedPrefs(String key, Context context){
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

    return preferences.getInt(key, 0);
}

然后确保您的上下文不为空,并在此处意识到我们正在使用defaultSharedPreferences

我希望这有帮助!