Search code examples
androidsqliteandroid-sqlitesqliteopenhelperandroid-sql

ArrayIndexOutOfBoundException to delete single record


I am using external database with prefilled data. The user can also perform CRUD operation in that database. But when I am deleting the record its throwing the Array out of bound exception. Here, is my snippet from code which I implemented for deleting the record.

String part[] = ((ItemModel) parent.getItemAtPosition(position)).getName().split("-");
String childQuery = "delete from Stock where item_id = (select id from Item where name = '" + part[0].trim() + "' and size = " + part[1].trim() + ")";
DBHelper.execute(childQuery);
String deleteQuery = "delete from Item where name  = '" + part[0].trim() + "' and size = " + part[1].trim() + " ";
DBHelper.execute(deleteQuery);
customAdapter.notifyDataSetChanged();
dismiss();

try {
    if (!TextUtils.isEmpty(InOutStockActivity.etInOutName.getText().toString())) {
        InOutStockActivity.etInOutName.setText("");
    }

    if (!TextUtils.isEmpty(TotalStockActivity.etTotalName.getText().toString())) {
        TotalStockActivity.etTotalName.setText("");
    }
} catch (NullPointerException e) {
    e.printStackTrace();
}
TastyToast.makeText(mContext, "Record Deleted Successfully.", TastyToast.LENGTH_LONG, TastyToast.DEFAULT);

Here, is error in my logcat.

java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at com.v.m.fragment.NameFragment$2$1.onClick(NameFragment.java:102)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

Thanks in advance.


Solution

  • The name does not contain a "-" but your code assumes that.