I am learning how to use a sql database in an Android activity. I am learning from this tutorial. I have an activity in which I use the database handler, from the tutorial.
I make a declaration of the variable inside of activity class.
DatabaseHandler db;
In the oncreate method I create a new DatabaseHandler object:
DatabaseHandler db = new DatabaseHandler(this);
I want to use the database after a button has been clicked. So I use the connection in the onClick method, but I get a null pointer exception unless I create a new object in the onclick. Why is that, with different type of objects I can declare variables like I did in this example.
The constructor of the DatabaseHandler is:
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
The super being SQLiteOpenHelper.
You’re getting the null exception because you’re instantiating incorrectly. you declared your db a field, but then instantiated a different object
DatabaseHandler db = new DatabaseHandler(this);<– as a local variable. Thus your onClick only has access to the uninstantiated field. to fix you need to replace what you have with this in your oncreate.or if the onClick is in onCreate, by applying the final modifier. (and removing the field object)