2013-03-25 29 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