I\'m relatively new to Java and am used to generics in C# so have struggled a bit with this code. Basically I want a generic method for getting a stored Android preference by ke
Try defining a bunch of functions with the same name that take a different type for the default, and let the compiler figure it out. Java really ties your hands when working with types, especially primitive types.
public function int getPreference( String key , int missing ) { return sharedPreferences.getInt( key , missing ); }
public function boolean getPreference( String key , boolean missing ) { return sharedPreferences.getBoolean( key , missing ); }
public function String getPreference( String key , String missing ) { return sharedPreferences.getString( key , missing ); }
Edit:
If you are trying to get an object (not primitive) regardless of the type, you can use:
public function Object getPreference( String key , Object missing ) { return sharedpreferences.contains( key ) ? sharedPreferences.getAll().get( key ) : missing; }
If you are trying to get a specific type like int regardless of what is stored, you can use:
public function int getPreference( String key , int missing ) {
int result = missing;
Object value = sharedpreferences.contains( key ) ? sharedPreferences.getAll().get( key ) : null;
if ( value instanceof Integer ) result = ((Integer)value).intValue();
if ( value instanceof Boolean ) result = ((Boolean)value).booleanValue() ? 1 : 0;
// repeat for every other primitive wrapper type you care about
return result;
}
If you are trying to get a result only if it is a certain type, you can use something like:
public function Object getPreference( Class inRequire , String key , Object missing ) {
Object value = sharedpreferences.contains( key ) ? sharedPreferences.getAll().get( key ) : null;
if ( !( value instanceof inRequire ) ) {
value = null;
}
return ( value == null ) ? missing : value;
}
It turns out the preference I'm trying to read is stored as a string so the cast exception is coming from inside the Android code not mine. Thanks for your help. But as I am a Java-newbie, if you think there is anything generally wrong with my routine, please teach me a better way.
May I suggest:
Integer i = new Integer(42);