我有一个简单的场景,但似乎无法绕过它。
每次用户点击某个项目时,我想将增加的值保存为SharedPreferences
,让我展示一下我的内容:
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();
}
}
});
所以,当我关闭活动并再次打开它时,计数器将重置为零,第一个保存到SharedPreferences
回到0.如果我保持活动打开并测试它,它工作,我得到了像预期的那样吐司。
有人可以指出我做错了吗?
答案 0 :(得分:2)
因为您在活动加载时从未将计数器设置回来。试试这个:
var result = list.Select(x => {
var parts = x.Split('_');
return parts.Length == 3 ? new Item { a1 = parts[0], a2 = parts[1], a3 = parts[2] : null };
}).Where(i => i != null).ToList();
答案 1 :(得分:0)
在代码中进行以下更改
@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();
}
}
});
}
我希望这对你有帮助,Happy Coding