gpt4 book ai didi

java - 组合字符串数组和迭代器并排序

转载 作者:行者123 更新时间:2023-12-01 18:05:39 26 4
gpt4 key购买 nike

我的应用程序中有 2 组值 - 1 组来自资源文件,1 组来自共享首选项。有没有一种简单的方法可以将这两者结合起来并为适配器创建排序列表?这是我的代码:

  Spinner copyFromCity = (Spinner) findViewById(R.id.spinner);


Resources res = getResources();
String [] predefinedCities = res.getStringArray(R.array.predefined_cities);

// Necessary to add Iterator String to an adapter
ArrayList<String> sortedPredefinedCities = new ArrayList<String>();
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
new ArrayList(Arrays.asList(predefinedCities)));


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

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

while(userCities.hasNext()){

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

/* TODO Way to sort both these values into alphabetical order */

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

添加 readCitiesFromPref() 方法以阐明返回 Iterator 的原因

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


} catch (NullPointerException e1) {

//TODO
}

return userCities;
}

最佳答案

我的想法是将这些数组/列表添加到List中,排序并将其设置为适配器

    String [] predefinedCities = res.getStringArray(R.array.predefined_cities);

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

List<String> copyOfCities = new ArrayList<String>();
while (userCities.hasNext()){

copyOfCities.add(userCities.next());

}

ArrayList<String> sortedCities = new ArrayList<String>();
sortedCities.addAll(copyOfCities);
sortedCities.addAll(Arrays.asList(predefinedCities));
Collections.sort(sortedCities);

ArrayAdapter<CharSequence> adapter = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
sortedCities);

关于java - 组合字符串数组和迭代器并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36638280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com