I want to use existing array element as switch case rather giving constant string value to switch case
I have values in resource string array that I used to display, and user has to select from these display values, now I want to compare the input value that I saved in shared preference and the values that I have in array resource, I wrote something like this but it didn't work
private static String activity;
private static int result;
activity = SharedPrefUtils.getActivityLevel(context);
String[] activities
= context.getResources().getStringArray(R.array.activity);
switch (activity){
//something like getting values from array
case activities[0]:
result = 0;
break;
case activities[1]:
result = 200;
break;
case activities[2]:
result = 300;
break;
}
return result;
Instead of iterating through an array
, you can convert it into a List
and use indexOf
to get the element index, eg:
String[] activities = context.getResources().getStringArray(R.array.activity);
List<String> activitiesList = Arrays.asList(activities);
int index = activitiesList.indexOf(activity);
This is what the javadoc says:
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
So, you can base your logic on index
value.
Another approach would be to use a Map<Integer, String>
and pass the Integer
key to the method based on whichever value is selected by a user.
First of all make sure your "activity" String and the items of "activities" array are returning you some values. Try to print the values to check that. If all of them are returning you values then you can compare String in this way:
if (activity.equalsIgnoreCase(activities[0]){
Log.e("Matched" , "Yeah, it matched");
}
You can match your all String values one by one in this way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.