第一次发帖,如有错误请见谅。也是Android的新手,我在试图找出共享偏好问题时遇到了问题。我声明我的常量如下
private static SharedPreferences mSharedPreferences;
static final String TWEET = null;
static final String MEAL_ID = null;
我的共同偏好如下
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
我的简单测试代码如下:
String msgTemp = "testing";
long iDTest = 234;
Editor e = mSharedPreferences.edit();
e.putLong(MEAL_ID, iDTest);
e.putString(TWEET, msgTemp);
e.commit();
String tempMsg = mSharedPreferences.getString(TWEET, "");
long tempId = mSharedPreferences.getLong(MEAL_ID, 0);
Toast.makeText(getApplicationContext(),
"Msg: " + tempMsg + " " + "ID: " + tempId, Toast.LENGTH_LONG).show();
返回以下错误:
03-25 15:47:41.386: E/AndroidRuntime(28321): java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long03-25 15:47:41.386: E/AndroidRuntime(28321): at android.app.SharedPreferencesImpl.getLong(SharedPreferencesImpl.java:228)
但是,如果我像这样切换代码中的 2 个“放置”行:
String msgTemp = "testing";
long iDTest = 234;
Editor e = mSharedPreferences.edit();
e.putString(TWEET, msgTemp);
e.putLong(MEAL_ID, iDTest);
e.commit();
String tempMsg = mSharedPreferences.getString(TWEET, "");
long tempId = mSharedPreferences.getLong(MEAL_ID, 0);
Toast.makeText(getApplicationContext(),
"Msg: " + tempMsg + " " + "ID: " + tempId, Toast.LENGTH_LONG).show();
我收到以下错误:
03-25 15:50:16.551: E/AndroidRuntime(28838): java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String 03-25 15:50:16.551: E/AndroidRuntime(28838): at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:205)
所以在我看来,这些值以错误的顺序输入到偏好中,但我不知道为什么。我尝试在输入新值之前清除这些值,如下所示:
String msgTemp = "testing";
long iDTest = 234;
Editor e = mSharedPreferences.edit();
e.remove(MEAL_ID);
e.remove(TWEET);
e.putLong(MEAL_ID, iDTest);
e.putString(TWEET, msgTemp);
e.commit();
String tempMsg = mSharedPreferences.getString(TWEET, "");
long tempId = mSharedPreferences.getLong(MEAL_ID, 0);
Toast.makeText(getApplicationContext(),
"Msg: " + tempMsg + " " + "ID: " + tempId, Toast.LENGTH_LONG).show();
但这也无济于事。任何人都可以为我阐明这一点吗?