我想知道为什么我的SharedPreference
方法不能保存我的数据
这是我的代码
保存功能(每次执行我的程序后都会调用此函数):
public void save(double tamt) {
SharedPreferences saveamount = getSharedPreferences("TotalAmount" , MODE_PRIVATE);
SharedPreferences.Editor editor = saveamount.edit();
editor.clear();
editor.putString("LastAmount",String.valueOf(tamt));
editor.apply();
}
我在onCreate()
方法中调用了阅读方法:
public void loadAmt() {
SharedPreferences loadamount = getSharedPreferences("TotalAmount" ,0);
String amt = loadamount.getString("TotalAmount","");
if (amt.matches("")){
return;
}
else {
total = Double.parseDouble(loadamount.getString("TotalAmount" ,"0"));
et.setText(String.valueOf(total));
}
}
是否因为保存或阅读方法?
每次退出程序并重新打开后,数据都不会显示。
答案 0 :(得分:3)
因为你保存
editor.putString("LastAmount",String.valueOf(tamt));
但你检索
String amt = loadamount.getString("TotalAmount","0");
它们是不同的键 你必须检索
String amt = loadamount.getString("LastAmount","");
而且:
total = Double.parseDouble(loadamount.getString("TotalAmount" ,"0"));
et.setText(String.valueOf(total));}
应改为
// USELESS, you already have the string in amt
//total = Double.parseDouble(loadamount.getString("TotalAmount" ,"0"));
et.setText(String.valueOf(amt));}
答案 1 :(得分:0)
您的错误是TotalAmount
是您的文件名,并且您正在尝试获取一个字符串TotalAmount
,该字符串不存在,因为您使用密钥{{1}保存了您的值}。所以只需修改加载方法
LastAmount
答案 2 :(得分:0)
在 loadAmt()方法中,您的密钥不适合获取偏好设置信息,请执行以下操作:
public void loadAmt()
{
SharedPreferences loadamount = getSharedPreferences("TotalAmount" ,0);
String amt = loadamount.getString("LastAmount",""); //change here to LastAmount
if (amt.matches("")){
return;
}
else {
total = Double.parseDouble(loadamount.getString("LastAmount" ,"0")); //change here to LastAmount
et.setText(String.valueOf(total));}
}
答案 3 :(得分:0)
以下是您的代码:
public void save(double tamt) {
SharedPreferences saveamount = getSharedPreferences("TotalAmount" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = saveamount.edit();
editor.clear();
editor.putString("LastAmount",String.valueOf(tamt));
editor.commit();}
我在OnCreate函数中使用了阅读功能
public void loadAmt()
{
SharedPreferences loadamount = getSharedPreferences("TotalAmount" ,Context.MODE_PRIVATE);
String amt = loadamount.getString("LastAmount","");
if (amt.matches("")){
return;
}else {
total = Double.parseDouble(loadamount.getString("LastAmount" ,"0"));
et.setText(String.valueOf(total));}
}