1

I have 2 APIs. From API1 I'm fetching a list of category names and setting it on spinner. From API2 I'm getting a category name, which I want to set as selected item in the spinner. But the problem is that the first time I'm not getting any position. When I go back to previous activity and come back to my activity, this time I'm getting the position.

private int getIndex(Spinner spinner, String myString){

    int index = 0;

    for (int i=0;i<spinner.getCount();i++){
        if (spinner.getItemAtPosition(i).equals(myString)){
            index = i;
        }
    }
    return index;
}
// API2's JSON parsing

if(newobj.getString("cat_name")!=null){
    int spinnerPosition = getIndex(catspin, newobj.getString("cat_name"));
    catspin.setSelection(spinnerPosition);                                    
}
Somnath Pal
  • 1,570
  • 4
  • 23
  • 42
  • 1
    Possible duplicate of [How to set selected item of Spinner by value, not by position?](http://stackoverflow.com/questions/2390102/how-to-set-selected-item-of-spinner-by-value-not-by-position) – Rahul Khurana Oct 19 '16 at 10:03
  • I tried the selected answer in the link but my app crashes with NPE that's why I'm using the method described by "Akhil Jain" in the same link. But I'm not getting the position the first time. – Somnath Pal Oct 19 '16 at 10:12
  • have you tried putting log in file? – Rahul Khurana Oct 19 '16 at 10:17

0 Answers0