I have this method in a class (non-activity) -
public boolean usernameChk(String usrname) {
String usrnmQuery = "SELECT * FROM " + TABLE_ACCOUNTS + " WHERE username = '" + usrname + "'";
SQLiteDatabase db = this.getReadableDatabase();
//NullPointerException on line above
Cursor cursor = db.rawQuery(usrnmQuery, null);
cursor.close();
if (cursor.getCount() <= 0) {
return false;
} else {
return true;
}
}
But I get NullPointerException on line SQLiteDatabase db = this.getReadableDatabase();
when I call this method from other activity -
private Context context;
this.context = context;
new DatabaseHandler(this);
DatabaseHandler dbz = new DatabaseHandler(context);
boolean z = dbz.usernameChk(username.getText().toString());
Here is my LogCat -
09-02 10:28:11.906: W/ApplicationPackageManager(9380): getCSCPackageItemText()
09-02 10:28:12.171: D/OpenGLRenderer(9380): Enabling debug mode 0
09-02 10:28:13.881: W/ApplicationPackageManager(9380): getCSCPackageItemText()
09-02 10:28:18.436: D/AndroidRuntime(9380): Shutting down VM
09-02 10:28:18.436: W/dalvikvm(9380): threadid=1: thread exiting with uncaught exception (group=0x4180ec08)
09-02 10:28:18.441: E/AndroidRuntime(9380): FATAL EXCEPTION: main
09-02 10:28:18.441: E/AndroidRuntime(9380): Process: com.Atlantiz.diary, PID: 9380
09-02 10:28:18.441: E/AndroidRuntime(9380): java.lang.NullPointerException
09-02 10:28:18.441: E/AndroidRuntime(9380): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
09-02 10:28:18.441: E/AndroidRuntime(9380): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
09-02 10:28:18.441: E/AndroidRuntime(9380): at com.Atlantiz.diary.DatabaseHandler.usernameChk(DatabaseHandler.java:142)
09-02 10:28:18.441: E/AndroidRuntime(9380): at com.Atlantiz.diary.Create.onClick(Create.java:42)
09-02 10:28:18.441: E/AndroidRuntime(9380): at android.view.View.performClick(View.java:4633)
09-02 10:28:18.441: E/AndroidRuntime(9380): at android.view.View$PerformClick.run(View.java:19330)
09-02 10:28:18.441: E/AndroidRuntime(9380): at android.os.Handler.handleCallback(Handler.java:733)
09-02 10:28:18.441: E/AndroidRuntime(9380): at android.os.Handler.dispatchMessage(Handler.java:95)
09-02 10:28:18.441: E/AndroidRuntime(9380): at android.os.Looper.loop(Looper.java:157)
09-02 10:28:18.441: E/AndroidRuntime(9380): at android.app.ActivityThread.main(ActivityThread.java:5356)
09-02 10:28:18.441: E/AndroidRuntime(9380): at java.lang.reflect.Method.invokeNative(Native Method)
09-02 10:28:18.441: E/AndroidRuntime(9380): at java.lang.reflect.Method.invoke(Method.java:515)
09-02 10:28:18.441: E/AndroidRuntime(9380): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
09-02 10:28:18.441: E/AndroidRuntime(9380): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
09-02 10:28:18.441: E/AndroidRuntime(9380): at dalvik.system.NativeStart.main(Native Method)
I know this type of question was asked before but the solutions given didn't work. Any ideas on how to fix it?
EDIT
Constructor -
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
And class -
package com.Atlantiz.diary;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "accountManager";
// Contacts table name
private static final String TABLE_ACCOUNTS = "accounts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_F_NAME = "first_name";
private static final String KEY_L_NAME = "last_name";
private static final String KEY_USERNAME = "username";
private static final String KEY_EMAIL = "email";
private static final String KEY_PASSWORD = "password";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_ACCOUNTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_F_NAME + " TEXT," +
KEY_L_NAME + " TEXT," + KEY_USERNAME + " TEXT," + KEY_EMAIL +
" TEXT," + KEY_PASSWORD + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACCOUNTS);
onCreate(db);
}
// Adding new contact
public void addContact(Accounts account) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_F_NAME, account.getFirst_name());
values.put(KEY_L_NAME, account.getLast_name());
values.put(KEY_USERNAME, account.getUsername());
values.put(KEY_EMAIL, account.getEmail());
values.put(KEY_PASSWORD, account.getPassword());
db.insert(TABLE_ACCOUNTS, null, values);
db.close();
}
// Getting single contact
public Accounts getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ACCOUNTS, new String[] { KEY_ID,
KEY_F_NAME, KEY_L_NAME, KEY_USERNAME, KEY_EMAIL, KEY_PASSWORD }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Accounts account = new Accounts(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
// return contact
return account;
}
// Getting All Contacts
public List<Accounts> getAllAccounts() {
List<Accounts> AccountList = new ArrayList<Accounts>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ACCOUNTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Accounts account = new Accounts();
account.setID(Integer.parseInt(cursor.getString(0)));
account.setFirst_name(cursor.getString(1));
account.setLast_name(cursor.getString(2));
account.setUsername(cursor.getString(3));
account.setEmail(cursor.getString(4));
account.setPassword(cursor.getString(5));
// Adding contact to list
AccountList.add(account);
} while (cursor.moveToNext());
}
// return contact list
return AccountList;
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_ACCOUNTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public boolean usernameChk(String usrname, Context context){
String usrnmQuery = "SELECT * FROM " + TABLE_ACCOUNTS + " WHERE username = '" + usrname + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(usrnmQuery, null);
cursor.close();
if(cursor.getCount() <= 0){
return false;
}else{
return true;
}
}
// Updating single contact
public int updateContact(Accounts account) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_F_NAME, account.getFirst_name());
values.put(KEY_L_NAME, account.getLast_name());
values.put(KEY_USERNAME, account.getLast_name());
values.put(KEY_EMAIL, account.getLast_name());
values.put(KEY_PASSWORD, account.getLast_name());
// updating row
return db.update(TABLE_ACCOUNTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(account.getID()) });
}
// Deleting single contact
public void deleteContact(Accounts account) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ACCOUNTS, KEY_ID + " = ?",
new String[] { String.valueOf(account.getID()) });
db.close();
}
}
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 :
You have not passed proper context of your activity that is why its throwing nullpointer error.
Just change your method as below.
Declare one common
Context
in yourDatabaseHelper
and assign the value of constructor in your while creating instance of your helper class as below:The
Context
you pass to yourDatabaseHandler
constructor isnull
.That's the explanation for the NPE in
getDatabaseLocked()
. To get help fixing that, post code where you initialize the 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