我目前正在尝试搜索数组列表并显示与用户查询匹配的结果。我继续得到一个ConcurrentModificationException,不知道如何解决它。我可搜索的活动中的代码如下:
public class SearchActivity extends Activity {
ListView l;
String[] testArray;
List<String> testArrayList;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
testArray = getResources().getStringArray(R.array.list);
testArrayList = new ArrayList<String>(Arrays.asList(testArray));
l = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, testArrayList);
l.setAdapter(adapter);
handleIntent(getIntent());
}
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//Log.d("Event", query);
search(query);
}
}
private void search(String query){
for (String element : testArrayList) {
if (!element.contains(query)) {
testArrayList.remove(element);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, menu);
return true;
}
}
答案 0 :(得分:0)
问题在于:
for (String element : testArrayList) {
if (!element.contains(query)) {
testArrayList.remove(element);
}
}
在迭代集合时不应删除元素,将其更改为此类(未测试):
Iterator<String> iter = testArrayList.iterator();
while(iter.hasNext()){
if (!iter.next().contains(query)) {
iter.remove();
}