I am trying to delete the selected item from a ListView and the Problem is that when I delete the selected content and refresh the Adapter the position of the remaining content changes, so because of that at some point of deleting the content again it gives IndexOutOfBoundsException. Can anyone tell me how to solve this problem?
Here is my code for deleting the selected item.
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = mActivity.getLayoutInflater();
view = inflator.inflate(R.layout.main, null);
final ViewHolder viewholder = new ViewHolder();
viewholder.tvTitle = (TextView) view.findViewById(R.id.txttitle);
viewholder.imgdelete = (ImageButton) view.findViewById(R.id.imgdelete);
viewholder.imgdelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
list.remove(position);
notifyDataSetChanged();
}
});
view.setTag(viewholder);
}
else
{
view = convertView;
}
ViewHolder viewholder = (ViewHolder) view.getTag();
viewholder.tvTitle.setText(list.get(position).getmTitle());
return view;
}
Here is my Logcat error
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): FATAL EXCEPTION: main
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): java.lang.IndexOutOfBoundsException: Invalid index 5, size is 5
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at java.util.ArrayList.remove(ArrayList.java:406)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at com.list.AdapterClass$1.onClick(AdapterClass.java:66)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at android.view.View.performClick(View.java:2408)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at android.view.View$PerformClick.run(View.java:8816)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at android.os.Handler.handleCallback(Handler.java:587)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at android.os.Handler.dispatchMessage(Handler.java:92)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at android.os.Looper.loop(Looper.java:123)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at android.app.ActivityThread.main(ActivityThread.java:4627)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at java.lang.reflect.Method.invokeNative(Native Method)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at java.lang.reflect.Method.invoke(Method.java:521)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-17 13:01:41.715: ERROR/AndroidRuntime(4284): at dalvik.system.NativeStart.main(Native Method)