当前位置: 动力学知识库 > 问答 > 编程问答 >

android - How to Store an int in SharedPreferences

问题描述:

In my first app, I am putting together a simple counter app where user taps a button to add one point to an int variable. I have tried to store the number of button taps permanently as a share preference but the result is not stored and it is reset to 0 each time the app is run agian. Here's my code. I really appreciate if you help me.

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;

}

}

网友答案:

You're saving the greed in the onCreate() method at the beginning. At that time, the value of the variable greed is 0 as it has not yet been initialized. Therefore, this value 0 gets stored. You're never updating the value of greed thereafter. Therefore, it remains 0.

Try this:

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)));

}
分享给朋友:
您可能感兴趣的文章:
随机阅读: