我在课堂上有这种方法(非活动) -
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();
}
}
答案 0 :(得分:6)
由于您的类不是活动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();
答案 1 :(得分:2)
您传递给Context
构造函数的DatabaseHandler
为null
。
这是getDatabaseLocked()
中对NPE的解释。要获得帮助,请在初始化上下文的位置发布代码。
答案 2 :(得分:1)
你没有传递适当的活动上下文,这就是它抛出nullpointer错误的原因。
只需更改您的方法,如下所示。
public boolean usernameChk(String usrname){
String usrnmQuery = "SELECT * FROM " + TABLE_ACCOUNTS + " WHERE username = '" + usrname + "'";
SQLiteDatabase db = this.getReadableDatabase();
在Context
中声明一个公共DatabaseHelper
,并在创建帮助程序类的实例时分配构造函数的值,如下所示:
public Context m_context;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
m_context = context;
}
答案 3 :(得分:1)
根据您的代码,未定义上下文。
在创建帮助程序的新实例时使用此而非上下文
DatabaseHandler dbz = new DatabaseHandler(this);
boolean z = dbz.usernameChk(username.getText().toString());
答案 4 :(得分:-1)
自3天以来,我一直遇到相同的错误。但是现在解决了。每当我想连接到数据库时,我都会创建数据库的新对象。 如果我在数据库中有10个函数,我会用10个不同的对象调用它们,因此不会给我错误