Domanda

i use setMultiChoiceItems for a list in a dialog. when click on ok the code is

 .setPositiveButton(R.string.alert_remove, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
String[] res = null;
for(int i=-1,l=usrCats.length; ++i<l;){
    if(selections[i])
       res[i] = usrCats[i].toString();
}
if(res != null && res.length>0)
   dbManager.removeUserShoppingCategories(res);
}       
})

i want to check if an item is selected with if(selections[i] and if so, add the name in a String

i am having a null pointer access in the res[i] = usrCats[i].toString() and a dead code warning in the last if statement.

i am using the last if, to check if there has been any selection so as to call my method.

what am i doing wrong?

È stato utile?

Soluzione

        .setPositiveButton(R.string.alert_remove, new DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int which){
        String[] res = null; // you initialised it with null
        for(int i=-1,l=usrCats.length; ++i<l;){ /*this line and the below line are condition 
    statemnts whose code may not run. so there are chances that your **res** will 
    remain initialised with null*/
            if(selections[i])
               res[i] = usrCats[i].toString();
        }
        if(res != null && res.length>0)// so here it shows a dead code warning.
           dbManager.removeUserShoppingCategories(res);
        }       
        })
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top