当前位置: 首页 > 面试题库 >

getReadableDatabase()上的NullPointerException

白烨煜
2023-03-14
问题内容

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

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 db = this.getReadableDatabase();当我从其他活动中调用此方法时,我会在线获取NullPointerException-

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

}

}

问题答案:

由于不是活动的类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 getReadableDatabase() 和 getWritableDatabase()分析对比,包括了Android getReadableDatabase() 和 getWritableDatabase()分析对比的使用技巧和注意事项,需要的朋友参考一下 Android getReadableDatabase() 和 getWritableDatabase()分

  • 问题内容: 我正在尝试根据此教程在我的应用程序中实现NotificationListenerService:http : //www.kpbird.com/2013/07/android- notificationlistenerservice.html ,但是调用getActiveNotifications时出现NullPointerException。 我正在向该服务发送广播,该广播应生成所有

  • 我试图根据以下教程在应用程序中实现NotificationListenerService:http://www.kpbird.com/2013/07/android-NotificationListenerService.html,但在调用GetActiveNotifications时出现了NullPointerException。 我正在向服务发送广播,该服务将生成所有通知的列表:

  • 我正在创建一个验证字段的服务。如果该字段不符合我的规则,我会抛出一个ResourceBusinessException,这是我创建的一个类,用于处理不可处理的实体。但是,当抛出此异常时,Spring在类AbstractMessageConverterMethodProcessor上抛出NullPointerException。 首先,我的Spring版: } 我的ResourceBusinessE

  • Animal.java 我为它创建了以下自定义断言: AnimalAssert.java 编辑:基于第一个答案(cglib需要一个),我用一个no arg构造函数更新了动物类,但是抛出了相同的异常

  • 我的应用程序一直在许多Android平台上报告这个问题(4.1、4.0.4、2.3.6.…)。但我无法在我的手机上复制这个问题。我已经在Google上搜索了这个问题,但堆栈跟踪似乎与我的不一样。