【发布时间】:2014-11-16 14:47:19
【问题描述】:
我有一个很奇怪的问题。
我使用键/值对来保存我的应用程序数据。它工作正常!我可以保存和获取字符串值和布尔值。
我无法获得的唯一值类型是整数
让我描述一下情况:
在一项活动中,我以这种方式保存我的键/值对:
addElement(getApplicationContext(), "all_tasks", Integer.parseInt(allTasks.getText().toString()));
我使用 KeyValueStorageHelper.java 文件中的这个方法:
/* Записать новую целочисленную пару */
public static void addElement(Context context, String key, int value) {
ContextWrapper contextWrapper = new ContextWrapper(context);
SharedPreferences.Editor sharedPreferences = contextWrapper.getSharedPreferences("MentalCalculationSaveData", ContextWrapper.MODE_PRIVATE).edit();
sharedPreferences.putInt(key, value);
sharedPreferences.apply();
}
之后,在另一个活动中,我尝试这样做,奇怪的是:
if (isKeyExists(getApplicationContext(), "all_tasks"))
Toast.makeText(getApplicationContext(), getInt(getApplicationContext(), "all_tasks"),Toast.LENGTH_LONG).show();
此代码引发“ResouceNotFound 异常”。好的。但这很奇怪。如果没有这样的资源,为什么我的 if-else 块返回 true?
之后我建议,这可能不是整数键/值对。
我试过这个:
Toast.makeText(getApplicationContext(), (int)getFloat(getApplicationContext(), "all_tasks"),Toast.LENGTH_LONG).show();
它再次抛出异常:
java.lang.Integer cannot be cast to java.lang.Float
那怎么了?当我试图获取它时,我的值怎么可能是 Integer 并引发异常?
【问题讨论】:
-
ResourceNotFoundException 在哪里引发?我认为您的代码不会在 if 块内执行。在 if 语句的条件下抛出异常