mardi 23 février 2016

Nullpointerexception when trying to open SQLite database

I am getting the following line in LogCat that seems to point to a null dbHelper when opening my SQLite DB.

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

Here is the chain of code listed in the Stacktrace (it references three lines):

  1. Instantiate a new Object:

    Vehicle v = new Vehicle(getActivity(), vId);
    
    
  2. Open the Datasource inside the Object to load existing properties

    public Vehicle(Context mContext, int vehicleId) {
    
    GasDataSource datasource = new GasDataSource(mContext);
    datasource.open(); // Line called in LogCat
    
    
  3. Do the actual Open method

    database = dbHelper.getWritableDatabase();
    
    
  4. Supplemental code: GasDataSource constructor:

    public GasDataSource(Context context) {
        dbHelper = new MySQLiteHelper(context);
    }
    
    

I don't understand how dbHelper can be null. The only thing I can think of was the context was null OR thedatabase was closed already because this happened as the app was in the background for a long time and when I opened it up and hit the 'save' button in the Activity (which triggers this code in part).

Can someone possibly identify the cause, if not, what the best way to at least do a null check here? it seems weird to do it on this line (I have never seen it done before in examples): dbHelper.getWritableDatabase();

Aucun commentaire:

Enregistrer un commentaire