SharedPreference ClassCastException问题Android

时间:2013-03-25 20:02:05

标签: java android

这里第一次发布海报,请原谅任何发布错误。也是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“put”行,如下所示:

    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();

但这也没有做任何事情。任何人都可以为我阐明这一点吗?

1 个答案:

答案 0 :(得分:5)

给你的常数值:

MEAL_ID =“meal_id”