如何将String Iterator值添加到ArrayAdapter?

时间:2016-04-14 18:20:35

标签: android iterator android-arrayadapter android-sharedpreferences

我正在尝试添加字符串迭代器和ArrayAdapter的值,但是没有得到正确的结果。这是我的代码:

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);

微调器只显示来自我的pref文件的值,而不是来自方法readCitiesFromPref()的额外String值;

我已经验证返回的Iterator字符串有值。在调试模式下,我能够看到这不会添加到适配器从首选项中的现有mObject中

由于

编辑:根据请求添加readCitiesFromPref()方法虽然我认为它是无关紧要的,因为返回值是准确的并且具有预期的字符串迭代器:

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;
}

1 个答案:

答案 0 :(得分:2)

问题出现在readCitiesFromPref中,因为当你创建迭代器时,你也在迭代所有的元素,只有在你返回迭代器后才会有hasNext() = null的值,因此,此代码while(userCities.hasNext()){ 永远不会被执行。要解决此问题,只需在加载所有值后返回迭代器。