First time poster here, so please forgive any posting errors. Also a newbie to Android and I am having an issue trying to figure out a sharedpreference problem. I declare my constants as follows
private static SharedPreferences mSharedPreferences;
static final String TWEET = null;
static final String MEAL_ID = null;
and my shared preference as follows
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
my simple test code is as follows:
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();
which returns the following error:
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)
however if I switch the 2 "put" lines in the code like this:
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();
I get the following error:
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)
So it seems to me that the values are being enter into the preferences in the wrong order but I don't know why. I've tried clearing the values prior to entering new values like this:
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();
but that did nothing either. Can anyone shed some light on this for me?
nullobject - I'm not sure why this is even possible, but apparently it is ;-)