我想从我的数据库处理程序文件中使用下面给定的删除功能。
删除函数(在 DatabaseHandler 文件中):
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",new String[] { String.valueOf(contact.getID()) });
db.close();
}
当我在另一个活动中实现它时。像这样:
String a = Integer.toString(_contactlist.get(position).getID());
viewHolder.txtid.setText(a.trim());
viewHolder.txt_name.setText(_contactlist.get(position).getName().trim());
viewHolder.txt_phone.setText(_contactlist.get(position).getPhoneNumber().trim());
final int temp = position;
Contact pm = db.getContact(temp); //temp is the position of the contact
db.deleteContact(pm);
但是当我使用它时,我遇到了一个意想不到的错误,即
日志猫:
08-19 19:21:25.468: W/System.err(304): android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
08-19 19:21:25.468: W/System.err(304): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
08-19 19:21:25.468: W/System.err(304): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
08-19 19:21:25.468: W/System.err(304): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
08-19 19:21:25.468: W/System.err(304): at com.parth.targetthebudget.DatabaseHandler.getContact(DatabaseHandler.java:80)
08-19 19:21:25.468: W/System.err(304): at com.parth.targetthebudget.ViewContact$ListAdapter$2$1.onClick(ViewContact.java:149)
08-19 19:21:25.468: W/System.err(304): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:163)
08-19 19:21:25.468: W/System.err(304): at android.os.Handler.dispatchMessage(Handler.java:99)
08-19 19:21:25.468: W/System.err(304): at android.os.Looper.loop(Looper.java:130)
08-19 19:21:25.468: W/System.err(304): at android.app.ActivityThread.main(ActivityThread.java:3687)
08-19 19:21:25.468: W/System.err(304): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 19:21:25.468: W/System.err(304): at java.lang.reflect.Method.invoke(Method.java:507)
08-19 19:21:25.468: W/System.err(304): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-19 19:21:25.468: W/System.err(304): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-19 19:21:25.468: W/System.err(304): at dalvik.system.NativeStart.main(Native Method)
问题:
它只剩下一个数据。并且最后一个数据根本没有删除,而是显示了上述错误
编辑(getContact();方法):
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}