2013-03-25 32 views
1

第一次在这里发布海报,所以请原谅任何发布错误。也是Android的新手,我有一个问题试图找出共享首选问题。我声明我的常数如下SharedPreference ClassCastException问题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) 

howev呃,如果我切换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(); 

但是那样做什么也没有。任何人都可以为我阐明这一点吗?

+2

你常数MEAL_ID和TWEET没有价值,所以你要2个不同的值,在SharedPreferences添加到同一个对象, 'null'对象 - 我不知道为什么这是可能的,但显然它是;-) – Darwind 2013-03-25 20:07:48

回答

5

给你的常数的值:

MEAL_ID =“meal_id”

+1

谢谢。每天学习更多。 – user2208939 2013-03-25 21:24:49

+0

我们都是从某个地方开始的。等到明年回顾这些问题时。美好时光 ;) – 2013-03-26 01:43:55