[英]increment and save incrementation in SharedPreferences
I have a simple scenario but can't seem to wrap my head around it. 我有一个简单的场景,但似乎无法解决这个问题。
I want to save a incremented value as a int to SharedPreferences
every time a user tap on a item, let me show what I have: 我想将每次用户点击项目时
SharedPreferences
量值保存为SharedPreferences
的int,让我展示一下我拥有的内容:
int counter = 0;
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
counter++;
SharedPreferences shareOpenClose = getSharedPreferences("Counter", Context.MODE_PRIVATE);
SharedPreferences.Editor editorOpenClose = shareOpenClose.edit();
editorOpenClose.putInt("count", counter);
editorOpenClose.apply();
SharedPreferences getCount = getSharedPreferences("Counter", Context.MODE_PRIVATE);
int getCountAmmount = getCount.getInt("count", 0);
if (getCountAmmount>3){
Toast.makeText(c, "success!", Toast.LENGTH_SHORT).show();
}
}
});
So, when I close the activity and open it again the counter will be reset to zero and the first save to SharedPreferences
back to 0. If I keep the activity open and test this it work and I get the toast as expected. 因此,当我关闭活动并再次打开它时,计数器将重置为零,并且第一个保存到
SharedPreferences
恢复为0。如果我保持活动打开并对其进行测试,则可以正常工作。
Can someone please point out what I'm doing wrong? 有人可以指出我做错了什么吗?
Because you never set the counter back when the activity loads. 因为您永远不会在活动加载时重新设置计数器。 try this:
尝试这个:
int counter = 0;
onCreate(...){
SharedPreferences countPref = getSharedPreferences("Counter", Context.MODE_PRIVATE);
counter = countPref.getInt("count", 0);
}
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
counter++;
SharedPreferences countPref = getSharedPreferences("Counter", Context.MODE_PRIVATE);
SharedPreferences.Editor editorOpenClose = countPref.edit();
editorOpenClose.putInt("count", counter);
editorOpenClose.apply();
if (counter>3){
Toast.makeText(c, "success!", Toast.LENGTH_SHORT).show();
}
}
});
Make the following changes in your code 在代码中进行以下更改
@Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences shareOpenClose = getSharedPreferences("Counter", Context.MODE_PRIVATE);
final SharedPreferences.Editor editorOpenClose = shareOpenClose.edit();
final int[] counter = {0};
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
counter[0]++;
editorOpenClose.putInt("count", counter[0]);
editorOpenClose.apply();
SharedPreferences getCount = getSharedPreferences("Counter", Context.MODE_PRIVATE);
int getCountAmmount = getCount.getInt("count", 0);
if (getCountAmmount>3){
Toast.makeText(c, "success!", Toast.LENGTH_SHORT).show();
}
}
});
}
I hope this will help you, Happy Coding 希望对您有帮助,快乐编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.