我正在尝试从列表视图中删除特定行,但我的应用程序不断崩溃。
首先,我尝试仅删除列表适配器中的项目,但它崩溃了:
listAdapter.remove(listAdapter.getItem(toDelete));
listAdapter.notifyDataSetChanged();
然后我也尝试直接从 listView 中删除它,但它也崩溃了:
listView.removeViewAt(toDelete);
listAdapter.notifyDataSetChanged();
toDelete 是一个整数变量,它具有我单击的行的编号 id。
那么如何从列表视图中删除特定行呢?
这是完整的代码,如果有人想要的话:
listView.setOnItemLongClickListener(new OnItemLongClickListener(){
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
deleteAlert.setTitle("Warning");
deleteAlert.setMessage("Are you sure you want to delete this?");
toDelete = arg2;
deleteAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
File directory = new File (externalStoragePath + File.separator + "Android/data/com.whizzappseasyvoicenotepad/");
File deleteFile = new File (directory, fileNames.get(toDelete) + ".mp3");
deleteFile.delete();
dialog.dismiss();
listView.removeViewAt(toDelete);
listAdapter.notifyDataSetChanged();
Log.i("TAG", "Deleting file: " + directory + fileNames.get(toDelete) + ".mp3");
}
});
扩展“它崩溃”部分真的很难。很简单:只要我点击“是”按钮,应用程序就会崩溃。如果有帮助,这里是 logcat 文件:
08-06 19:05:07.437: E/AndroidRuntime(16257): FATAL EXCEPTION: main
08-06 19:05:07.437: E/AndroidRuntime(16257): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
08-06 19:05:07.437: E/AndroidRuntime(16257): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
08-06 19:05:07.437: E/AndroidRuntime(16257): at java.util.ArrayList.get(ArrayList.java:308)
08-06 19:05:07.437: E/AndroidRuntime(16257): at com.whizzappseasyvoicenotepad.RecordedLibrary$2$1.onClick(RecordedLibrary.java:113)
08-06 19:05:07.437: E/AndroidRuntime(16257): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
08-06 19:05:07.437: E/AndroidRuntime(16257): at android.os.Handler.dispatchMessage(Handler.java:99)
08-06 19:05:07.437: E/AndroidRuntime(16257): at android.os.Looper.loop(Looper.java:137)
08-06 19:05:07.437: E/AndroidRuntime(16257): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-06 19:05:07.437: E/AndroidRuntime(16257): at java.lang.reflect.Method.invokeNative(Native Method)
08-06 19:05:07.437: E/AndroidRuntime(16257): at java.lang.reflect.Method.invoke(Method.java:525)
08-06 19:05:07.437: E/AndroidRuntime(16257): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-06 19:05:07.437: E/AndroidRuntime(16257): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-06 19:05:07.437: E/AndroidRuntime(16257): at dalvik.system.NativeStart.main(Native Method)