【问题标题】:How to add String Iterator values to an ArrayAdapter?如何将字符串迭代器值添加到 ArrayAdapter?
【发布时间】:2016-08-06 11:20:52
【问题描述】:

我正在尝试将字符串迭代器的值添加到 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(); 的额外字符串值;

我已经验证了返回的迭代器字符串有值。在调试模式下,我可以看到这没有添加到适配器从首选项中拥有的现有 mObjects 中

谢谢

编辑:根据请求添加 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;
}

【问题讨论】:

  • 我们需要看readCitiesFromPref()方法

标签: android iterator android-arrayadapter android-sharedpreferences


【解决方案1】:

问题出在readCitiesFromPref,因为当您创建迭代器时,您也在迭代所有元素,并且只有在此之后您才返回迭代器,该迭代器将具有hasNext() = null 的值,并且出于这个原因这段代码while(userCities.hasNext()){ 永远不会被执行。要解决此问题,只需在加载所有值后返回迭代器即可。

【讨论】:

  • 不幸的是,当我返回 userCities 而不进行迭代时,我得到一个 java.lang.UnsupportedOperationException 试图将其添加到适配器
  • 基本上我找到了这个答案stackoverflow.com/questions/3476723/… - 但我不清楚如何在创建我的 ArrayAdapter 时实现它。非常感谢您的帮助
  • 没关系,我找到了办法——stackoverflow.com/a/11040777/5662769
猜你喜欢
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多