我想将一个ListView中的clicked元素替换为另一个,但是有一个问题:没有方法可以从ListView中操作它,当我更改适配器时 - 它给了我ConcurrentModificationException,因为我在onItemClick中更改了它。这是代码中的问题部分。
datasource = new IngredientsDataSource(this);
datasource.open();
final List<Ingredient> values_ing = datasource.getAllIngredients();
final List<Ingredient> values_ch = values_ing.subList(0, 0);
final ArrayAdapter<Ingredient> adapter_ing = new ArrayAdapter<Ingredient>(this, android.R.layout.simple_list_item_1, values_ing);
list_ing.setAdapter(adapter_ing);
final ArrayAdapter<Ingredient> adapter_ch = new ArrayAdapter<Ingredient>(this, android.R.layout.simple_list_item_1, values_ch);
list_ch.setAdapter(adapter_ch);
list_ing.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View itemClicked, int position, long id) {
final Ingredient item = values_ing.get((int)id);
list_ing.post(new Runnable() {
@Override
public void run() {
values_ing.remove(item);
adapter_ing.notifyDataSetChanged();
}
});
list_ch.post(new Runnable() {
@Override
public void run() {
values_ch.add(item);
adapter_ch.notifyDataSetChanged();
}
});
这里是Logcat
03-18 15:18:08.971 1027-1027/com.kochmarevsevolod.lazycook E/AndroidRuntime: FATAL EXCEPTION: main
java.util.ConcurrentModificationException
at java.util.AbstractList$SubAbstractList.size(AbstractList.java:360)
at java.util.AbstractList.add(AbstractList.java:425)
at com.kochmarevsevolod.lazycook.Search_Page$1$2.run(Search_Page.java:73)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
试试这个:
final Ingredient item = values_ing.get((int)id);
list_ing.post(new Runnable() {
@Override
public void run() {
values_ing.remove(item);
adapter_ing.notifyDataSetChanged();
}
});
list_ch.post(new Runnable() {
@Override
public void run() {
values_ch.add(item);
adapter_ch.notifyDataSetChanged();
}
});