0

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.

0

1 Answer 1

1

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.

db = new DatabaseHandler(this);

or if the onClick is in onCreate, by applying the final modifier. (and removing the field object)

Sign up to request clarification or add additional context in comments.

1 Comment

@mango how to use db = new DatabaseHandler(this); out of any activity such as custom class for work with database?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.