Skip to content

Android java : Error on SQLiteDatabase db = this.getWritableDatabase();

Am a beginner at android java.

Error on SQLiteDatabase db = this.getWritableDatabase(); line in

public boolean deleteItem(Todomodel todomodel){

    SQLiteDatabase db = this.getWritableDatabase(); //HERE
    ContentValues cv = new ContentValues();
    int numb = todomodel.getId();
    String whereClause = "id=?";
    String whereArgs[] = {String.valueOf(numb)};
    db.delete("CUSTOMER_TABLE", whereClause, whereArgs);
    db.close();

    return false;
}

ERROR :

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.monday, PID: 9794
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
        at android.content.ContextWrapper.getDatabasePath(ContextWrapper.java:330)
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:292)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:238)
        at com.example.monday.database.deleteItem(database.java:72)

I already had called the getWritabledatabase in the insert function. But when I try to write again. It doesn’t work.

Answer

You need to pass a valid Context to your SQLiteOpenHelper constructor.