1

I'm trying to put an IF statement for each array index value, the value is from MultiSelectList preference. but I'm having problem on doing it, here is my code please help me.

public void displaySelectedDoa(View view) {

mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Set<String> selectionsDoa = mySharedPreferences.getStringSet("selectedDoaKey", null);
String[] selectedDoa = selectionsDoa.toArray(new String[]{});

if (selectedDoa == "0") { // if index number = 0
    //do something at here
}
if (selectedDoa == "1") { // if index nuber = 1
    //do here
}

}

this is my MultiSelectList from preference fragment

<MultiSelectListPreference
    android:title="Select Doa"
    android:summary="select your doa"
    android:key="selectedDoaKey"
    android:entries="@array/select_doa"
    android:entryValues="@array/select_doa_value"/>
Ar Doe
  • 35
  • 1
  • 8

2 Answers2

0

selectedDoa is an array not a single string value so you will need to check all the selected indices try this

for (int i=0;i<selectedDoa.length;i++){
        String index=selectedDoa[i];
        switch (index){
            case "0":
                //do what zero does
                continue;
            case "1":
                //do what one does
                continue;
        }
    }

as our friend Vaiden said if switch string are an issue

replace them with

if(index.equals("0"){
//do what zero does
}
else if(index.equals("1"){
//do what one does
}
Hala.M
  • 766
  • 6
  • 15
  • 1
    Switch blocks with Strings are only supported on API >= 19 (http://stackoverflow.com/a/19722741/606351). For older Androids either parse the String to an int, or use cascaded IF statements with .equals() – Vaiden Sep 04 '16 at 15:21
  • on the String index = selectedDoa[ I ]; there is an error saying incompatible type . Required:java.lang.String Found:Java.lang.CharSequence . how to repair this ? – Ar Doe Sep 04 '16 at 21:29
  • hi it is selectedDoa[i]; also the code is compiling fine i tested it on android studio mySharedPreferences.getStringSet("selectedDoaKey", null); String[] selectedDoa = selectionsDoa.toArray(new String[]{}); for (int i = 0; i < selectedDoa.length; i++) { String index = selectedDoa[i]; if (index.equals("0")) { } else if (index.equals("1")) { } } – Hala.M Sep 04 '16 at 21:34
0

try this.

CharSequence[] selectedDoa = selectionsDoa.toArray(new String[]{});
    for (int i = 0; i < selectedDoa.length; i++){
        String index = selectedDoa[i].toString();
    }

 if (index.equals("string")){
//do here
}
HesZrave
  • 58
  • 7