Reputation: 16780
I have a couple of ListPreferences that my PreferenceActivity displays. From the class that launches this activity, I listen to any changes on the SharedPreferences and use getString(String key, String default) to obtain the selected option.
When I retrieve this String, I need to perform certain operations depending on what String it is. But, how would I use the String. If it was an int, I could have used switch case but what do I do with Strings?
Is there any other way apart from using if-else and using String.equals to compare the 2 strings? Or is there a way to retrieve the selected position instead of the selected String?
Upvotes: 0
Views: 165
Reputation: 822
If you must have an int signifying the position, you could use a String array and the Arrays.binarySearch method
private static final String[] VALUES = { "a", "b", "c", "d", "e" };
public void processSelection( String selectedValue ) {
int pos = Arrays.binarySearch( VALUES, selectedValue );
switch (pos) {
case 0:
...
break;
default:
break;
}
}
Upvotes: 0
Reputation: 11107
int k = 0;
String i = "Namratha"; // replace the value from Shared Preference
try {
k = Integer.parseInt(i);
} catch (Exception e) {
Log.v("Exception**********", e.getMessage());
}
See if value is String it will throws Exception and go to catch block so that you can understand calue from preference is String.. Do you stuffs inside catch block accordingly..
Else if the value is int then do your stuffs inside try block.
Upvotes: 1
Reputation: 15052
You can store all your String
s into a HashMap
, along with corresponding int
values and then have a switch
case on the int
.
Upvotes: 1