Android two different types of SharedPreference with the same id

I currently want to store two different data types as SharedPreference in my android app. Is it possible to store them with the same key value?


int id = 123;
myBoolean = false;
myString = "hello";

SharedPreferences.Editor edit = this.getSharedPreferences("MyPrefs", MODE_PRIVATE).edit();
edit.putString(String.valueOf(id), myString);
edit.putBoolean(String.valueOf(id), myBoolean);


because currently when I try to get a string value I get a ClassCast exception:

SharedPreferences settings = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String myString = settings.getString(String.valueOf(123), "def");


I am getting this exception:

java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String



source to share

1 answer

Not possible, Shared Preferences is a key value pair (key is unique). What your code does is replace the previous stored value. So when you try to get a value, you get a boolean value.



All Articles