Skip to content Skip to sidebar Skip to footer

Null Pointer Exception With Room Database

I am developing an android app using android studio my app has ROOM database when i store in the database a run time error appears and I can not solve it this is my database code

Solution 1:

Your Context is null, it would be better if you create a Context parameter in your getInstance() method instead of storing it in your CartDatabase class.

Try the following code

publicstatic CartDatabase getInstance(Context context) {
    if (instance == null) {
        instance = Room.databaseBuilder(context, CartDatabase.class, "Cart")//if we want in memory builder  ithink we can add it here
                .allowMainThreadQueries().build();
    }
    return instance;
}

Then on your onClick()

CartDatabase.getInstance(getApplicationContext()).cartDAO().insertToCart(cart);

Solution 2:

Add a constructor and pass context to it from the activity:

In your activity:

CartDatabasecart=newCartDatabase(this);

and in the CartDatabase class :

publicCartDatabase(Context             context){
    this.context=context;
     }

or pass context to the class using getInstance from your activity:

CartDatabase.getInstanse(this).cartDAO().insertToCart( cart);

and in the CartDatabase class :

publicstatic CartDatabase getInstance(Context context) ...

Solution 3:

You are getting this because you are not passing any context to the CartDatabase. You can simply add a context parameter to your getInstance method like that...

publicstatic CartDatabase getInstance(Context context) {
if (instance == null) {
    instance = Room.databaseBuilder(context, CartDatabase.class, "Cart").allowMainThreadQueries().build();
}
return instance;

}

And then need to call from activity like that...

CartDatabase.getInstance(getApplicationContext()).cartDAO().insertToCart(cart);

Post a Comment for "Null Pointer Exception With Room Database"