Skip to content Skip to sidebar Skip to footer

Getting Null Pointer Exception In Sqlitedatabase.query Method

I know this is a pre-asked question. But still I am not able to find solutions. I am opening a database with a SQLiteOpenHelper and applying insert and query method in SQLiteDataba

Solution 1:

Since you call a static method from a class that extends Activity, the onCreate method of that class is obviously not called, that's why you are getting NPE.

Firstly move all your methods in the utility class to your MovieDbHelper class, and use the context provided in the constructor.

publicclassMovieDbHelperextendsSQLiteOpenHelper {
    private Context context;
    privatestaticfinalintDATABASE_VERSION=2;
    staticfinalStringDATABASE_NAME="movie.db";

    publicMovieDbHelper(Context context) {
         super(context, DATABASE_NAME, null, DATABASE_VERSION);
         this.context = context;
    }
}

for example your getEntry (put it in the MovieDbHelper) can be rewritten as:

publicCursorgetEntry(String[] columns){
    SQLiteDatabase db = this.getReadableDatabase();
    return db.query("MOVIE",columns,null,null,null,null,null);  **--  nullpointer** 
}

EDITED:

usage in your activity:

MovieDbHelperhelper=newMovieDbHelper(YourActivityName.this);
String[] cm = {"mov_pos"};
Cursorc= helper.getEntry(cm);

usage in your fragment:

MovieDbHelperhelper=newMovieDbHelper(getActivity().getApplicationContext());
String[] cm = {"mov_pos"};
Cursorc= helper.getEntry(cm);

EDIT 2:

publicaddEntry( byte[] image)throws SQLiteException {
    SQLiteDatabasedb=this.getWritableDatabase();
    ContentValuescv=newContentValues();

    cv.put("mov_pos",   image);

    try {
        db.insertOrThrow("MOVIE", null, cv );
    } catch (SQLiteConstraintException e) {
        e.printStackTrace();
        returnfalse;
    }
    returntrue;
}

Post a Comment for "Getting Null Pointer Exception In Sqlitedatabase.query Method"