I have this method in a class (non-activity) -
public boolean usernameChk(String usrname) {
String usrnmQuery = \"SELECT * FROM \" + TABLE_ACCOUNTS + \"
The Context you pass to your DatabaseHandler constructor is null.
That's the explanation for the NPE in getDatabaseLocked(). To get help fixing that, post code where you initialize the context.
As your class which is not an Activity this.getReadableDatabase(); is firing NullPointerException as it is not getting context to open database.
Use context to open database. try with following :
DatabaseHandler dbz = new DatabaseHandler(Activity.this);
public Context context;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// assigning context Change your constructor
this.context = context;
}
// Open database using context object
SQLiteDatabase db = this.getReadableDatabase();
You have not passed proper context of your activity that is why its throwing nullpointer error.
Just change your method as below.
public boolean usernameChk(String usrname){
String usrnmQuery = "SELECT * FROM " + TABLE_ACCOUNTS + " WHERE username = '" + usrname + "'";
SQLiteDatabase db = this.getReadableDatabase();
Declare one common Context in your DatabaseHelper and assign the value of constructor in your while creating instance of your helper class as below:
public Context m_context;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
m_context = context;
}
I was getting the same error since 3 days. But it is solved now. I created a new object of the database whenever i want to connect to the database. If i have 10 functions in database, i will call them with 10 different objects hence not giving me the error
According to your code the context is not defined.
use this instead of context when creating a new instance of your helper
DatabaseHandler dbz = new DatabaseHandler(this);
boolean z = dbz.usernameChk(username.getText().toString());