Search code examples
androidnullpointerexceptionandroid-sqliteandroid-database

When i call an item from SQLite Database by its id, "SQLiteDatabase db = this.getReadableDatabase()" causes error: a null object reference


I have a sql database which i think to save students'name and their numbers. I can easily add item to the database, and can easily list them. However, when i want to call an specific item by its id,i get the following error:

java.lang.NullPointerException: Attempt to invoke virtual method'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference

and my emulator points that line:

SQLiteDatabase db = this.getReadableDatabase();

PART: getId(int id)

  public StudentsinLib getId(int id){

    String selectQuery = "SELECT * FROM " + STUDENTDATABASETABLE_NAME + " WHERE "+ COL + " ="+id;

    SQLiteDatabase db = this.getReadableDatabase(); // ======> THE EMULATOR POINTS HERE
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor != null)
        cursor.moveToFirst();

    StudentsinLib studentsinLib = new StudentsinLib();
    studentsinLib.setId(cursor.getInt(0));
    studentsinLib.setName(cursor.getString(1));
    studentsinLib.setNumber(cursor.getString(2));

    //log
    Log.d("getStudent(" + id + ")", StudentsinLib.toString());
    // 5. return student
    return studentsinLib;
}

My whole codes in my SQLiteDatabase

public class StudentsinLibDatabase extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String STUDENTDATABASE_NAME = "StudentsinLibDB";
// Table Content
private static final String STUDENTDATABASETABLE_NAME = "StudentsinLibTB";
private static String COL = "studentsinLibId";
private static String COL1 = "StudentsinLibName";
private static String COL2 = "studentsinLibNumber";

private static final String[] COLUMNS = {COL,COL1,COL2};
public Context context;

public StudentsinLibDatabase(Context context) {
    super(context, STUDENTDATABASETABLE_NAME, null, DATABASE_VERSION);
    this.context=context;
}
@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_TABLE = "CREATE TABLE "+STUDENTDATABASETABLE_NAME+"("
            +COL+" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
            +COL1+" TEXT,"
            +COL2+" TEXT);";

    db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older students table if existed
    db.execSQL("DROP TABLE IF EXISTS students");

    // create fresh students table
    this.onCreate(db);
}
public void addStudentstoLib(StudentsinLib studentstoLib){

    Log.d("addStudent", studentstolib.toString());

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value

    ContentValues values = new ContentValues();
    values.put(COL, studentstolib.getId());
    values.put(COL1, studentstolib.getName());
    values.put(COL2, studentstolib.getNumber());

    // 3. insert
    db.insert(STUDENTDATABASETABLE_NAME, // table
            null, //nullColumnHack
            values); // key/value -> keys = column names/ values = column values

    // 4. close
    db.close();
}
public StudentsinLib getId(int id){

    String selectQuery = "SELECT * FROM " + STUDENTDATABASETABLE_NAME + " WHERE "+ COL + " ="+id;

    SQLiteDatabase db = this.getReadableDatabase(); // ======> the emulator points here
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor != null)
        cursor.moveToFirst();

    StudentsinLib studentsinLib = new StudentsinLib();
    studentsinLib.setId(cursor.getInt(0));
    studentsinLib.setName(cursor.getString(1));
    studentsinLib.setNumber(cursor.getString(2));

    //log
    Log.d("getStudent(" + id + ")", StudentsinLib.toString());
    // 5. return student
    return studentsinLib;
}

public void deleteStudentinLib(int id){
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(StudentsinLibDatabase, COL + " = ?",
            new String[]{String.valueOf(id)});
    db.close();
}

public int updateStudent(StudentsinLib studentsinLib) {
    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put(COL, studentsinLib.getId());
    values.put(COL1,studentsinLib.getName());
    values.put(COL2,studentsinLib.getNumber());

    // 3. updating row
    int i = db.update(STUDENTDATABASETABLE_NAME, //table
            values, // column/value
            COL + " = ?", // selections
            new String[]{String.valueOf(studentsinLib.getId())}); //selection args
    // 4. close
    db.close();
    return i;
}

public ArrayList<StudentsinLib> getAllStudentsinLib() {
    ArrayList<StudentsinLib> studentsinLibs = new ArrayList<StudentsinLib>();
    // 1. build the query
    String query = "SELECT * FROM " + STUDENTDATABASETABLE_NAME;
    // 2. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    // 3. go over each row, build student and add it to list
    while (cursor.moveToNext()) {
        StudentsinLib studentsinLib = new StudentsinLib();
        studentsinLib.setId(cursor.getInt(0));
        studentsinLib.setName(cursor.getString(1));
        studentsinLib.setNumber(cursor.getString(2));
        studentsinLibs.add(studentsinLib);
    }
    Log.d("getAllStudents()", studentsinLibs.toString());
    // return student
    return studentsinLibs;
  }
}

What i have tried before is here:

NullPointerException at this.getReadableDatabase();

NullPointerException on getReadableDatabase()

Sqlitedatabase query not working when selecting by _id

That's all of my story, thank you in advance...


Solution

  • The Context argument you're passing to your StudentsinLibDatabase constructor is null.