如何在SharedPreferences中存储int

时间:2016-06-13 11:58:41

标签: android sharedpreferences android-sharedpreferences

在我的第一个应用程序中,我正在整理一个简单的计数器应用程序,用户点击按钮将一个点添加到int变量。我试图永久存储按钮点按钮的数量作为共享首选项,但结果不存储,每次应用程序运行时都会重置为0。这是我的代码。如果你帮助我,我真的很感激。

public class counter extends AppCompatActivity {

    public int greed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SharedPreferences counter = getApplicationContext().getSharedPreferences("uk.me.forus.lifetracker", Context.MODE_PRIVATE);
        counter.edit().putInt("greed", greed).apply();
        Log.i("Test: ", Integer.toString(counter.getInt("greed", greed)));

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_counter);
    }

    public void greed (View view){

        greed += 1;

    }
}

1 个答案:

答案 0 :(得分:0)

您开始在greed方法中保存onCreate()。那时,变量greed的值为0,因为它尚未初始化。因此,存储该值0。你永远不会更新贪婪的价值。因此,它仍为0。

试试这个:

private int greed;
private SharedPreferences counter;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_counter);

    counter = getApplicationContext().getSharedPreferences("uk.me.forus.lifetracker", Context.MODE_PRIVATE);

    //start the value of greed from what it was earlier.
    greed = counter.getInt("greed",0);

}

public void greed (View view){

    greed += 1;

    //update and print the value of greed everytime you increment it:
    counter.edit().putInt("greed", greed).apply();
    Log.i("Test: ", Integer.toString(counter.getInt("greed", greed)));

}