1

I am trying to add the values of a string iterator an ArrayAdapter and am not getting the right results. Here is my code:

Spinner copyFromCity = (Spinner) findViewById(R.id.spinner);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.predefined_cities, android.R.layout.simple_spinner_item);


    // Add values from our custom cities onto the Adapter via SharedPreferences

    prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
    Iterator<String> userCities = readCitiesFromPref();

    while(userCities.hasNext()){

        adapter.add(userCities.next());
    }


    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    copyFromCity.setAdapter(adapter);

The spinner only shows values from my pref file and not the extra String values coming from the method readCitiesFromPref();

I've already verified that the Iterator String returned has values. In debug mode, I"m able to see that this is not added to the existing mObjects that the adapter has from the preferences

Thanks

Edit: Adding readCitiesFromPref() method as per request though I maintain that it is irrelevant because the return value is accurate and has an iterator of strings as expected:

protected Iterator<String> readCitiesFromPref() {

    // See if preferences store this
    JSONObject citiesList = null;
    Iterator<String> userCities = null;
    try {

        // Yes, so get the values out
        citiesList = new JSONObject(prefs.getAll());

        userCities = citiesList.keys();

        while (userCities.hasNext()) {

            Log.i("Ram = ", userCities.next());
        }

    } catch (NullPointerException e1) {

        //
    }

    return userCities;
}
zooter
  • 2,128
  • 1
  • 13
  • 23

1 Answers1

2

The problem is in the readCitiesFromPref because when you are creating the iterator, you are also iterating all the elements and only after that you are returning the iterator, which will have the value for hasNext() = null, and from this reason this code while(userCities.hasNext()){ will never get executed. To fix this, simply return the iterator after all values are loaded.

Iulian Popescu
  • 2,595
  • 4
  • 23
  • 31
  • unfortunately when I return the userCities without doing the iteration, I"m getting a java.lang.UnsupportedOperationException trying to add this to the adapter – zooter Apr 15 '16 at 03:41
  • basically I found this answer http://stackoverflow.com/questions/3476723/why-cant-one-add-remove-items-from-an-arrayadapter - but am unclear how to implement this in creation of my ArrayAdapter. Help would be much appreicated – zooter Apr 15 '16 at 03:53
  • never mind, I found the way to do this -- http://stackoverflow.com/a/11040777/5662769 – zooter Apr 15 '16 at 04:00