2013-08-18 65 views
1

我想在我的Database Handler文件中使用下面給出的刪除函數。當我實現它時,javaNullpointerException即將到來。我絕對錯過了一些東西。如何在sqlite中調用delete函數

刪除功能:

// 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(); 
} 

我試圖儘可能使用:

 DatabaseHandler db = new DatabaseHandler(this); 
Contact pm = null; 
Intent i; 
i = getIntent(); 
pm._id= i.getExtras().getInt("id"); 
pm._name = i.getExtras().getString("name"); 
pm._phone_number = i.getExtras().getString("phone_number"); 

     // **Some problem is here I am not getting it 

         db.deleteContact(pm); 
         Toast.makeText(getApplicationContext(),"Deleted..",Toast.LENGTH_SHORT).show(); 

logcat的:

08-19 01:15:00.726: E/AndroidRuntime(12657): FATAL EXCEPTION: main 
08-19 01:15:00.726: E/AndroidRuntime(12657): java.lang.NullPointerException 
08-19 01:15:00.726: E/AndroidRuntime(12657): at com.parth.targetthebudget.ViewContact$ListAdapter$2$1.onClick(ViewContact.java:151) 
08-19 01:15:00.726: E/AndroidRuntime(12657): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:163) 
08-19 01:15:00.726: E/AndroidRuntime(12657): at android.os.Handler.dispatchMessage(Handler.java:99) 
08-19 01:15:00.726: E/AndroidRuntime(12657): at android.os.Looper.loop(Looper.java:130) 
08-19 01:15:00.726: E/AndroidRuntime(12657): at android.app.ActivityThread.main(ActivityThread.java:3687) 
08-19 01:15:00.726: E/AndroidRuntime(12657): at java.lang.reflect.Method.invokeNative(Native Method) 
08-19 01:15:00.726: E/AndroidRuntime(12657): at java.lang.reflect.Method.invoke(Method.java:507) 
08-19 01:15:00.726: E/AndroidRuntime(12657): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
08-19 01:15:00.726: E/AndroidRuntime(12657): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625) 
08-19 01:15:00.726: E/AndroidRuntime(12657): at dalvik.system.NativeStart.main(Native Method) 

回答

2

從我知道你正在試圖從1活動發送數據到另一個,所以你可以刪除匹配數據的記錄?

你有聯繫pm = null; 然後您試圖獲取數據庫中的空記錄的ID。 我確定你下面這個 http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/ 刪除

Contact pm = null; 
pm._id= i.getExtras().getInt("id"); 
pm._name = i.getExtras().getString("name"); 
pm._phone_number = i.getExtras().getString("phone_number"); 

添加

Contact pm = db.getContact(i.getExtras().getInt("id")); 

,將刪除具有從你的意圖

+0

是發送的內容相同ID的記錄,我已經嘗試這一點,但問題是,如果我已經給ID = 1那麼logcat顯示08-19 01:40:20.351:E/AndroidRuntime(13678):android.database.CursorIndexOutOfBoundsException:索引0請求,大小爲0 這意味着它不會刪除ID = 1的數據! – arraystack

+0

你確定有一個ID爲1的記錄嗎? –

相關問題