java-getReadableDatabase()上的NullPointerException

我在课堂上有这种方法(不活动)-

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;
    }

}

但是我在行SQLiteDatabase上得到了NullPointerException db = this.getReadableDatabase();当我从其他活动中调用此方法时-

private Context context;
this.context = context;
new DatabaseHandler(this);

DatabaseHandler dbz = new DatabaseHandler(context);
boolean z = dbz.usernameChk(username.getText().toString());

这是我的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)

我知道以前曾问过这种类型的问题,但给出的解决方案没有用.关于如何解决它的任何想法?

编辑

构造函数-

public DatabaseHandler(Context context) {
       super(context, DATABASE_NAME, null, DATABASE_VERSION);
   }

和课-

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();

}

}

解决方法:

作为您的不是Activity的类,this.getReadableDatabase();正在触发NullPointerException,因为它没有获取上下文来打开数据库.

使用上下文打开数据库.尝试以下:

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();
上一篇:android-在“启动项目”期间发生内部错误.显示java.lang.NullPointerException


下一篇:java – 带有null Long的三元表达式中的NullPointerException