在SQLite数据库上执行查询时出现android NullPointerException

时间:2012-04-09 09:05:20

标签: android sqlite nullpointerexception

我正在尝试从我创建的数据库中读取数据,但在尝试获取所有记录时总是会出现NullPointerException。

我几乎从另一个我完全运行的应用程序中复制了代码,但不知怎的,我在这里做错了。

NullPointerException位于

return mDb.query(DATABASE_TABLE_LOCALLOGIN, new String[] {LOCALLOGIN_ID, LOCALLOGIN_LOGIN, LOCALLOGIN_PASSWORD}, null, null, null, null, null);

这是相关代码(不介意字符串数组,以后用于添加表格: GoingOutDbAdapter.java

public class GoingOutDbAdapter {
private static final String DATABASE_NAME = "GoingOutData";
private static final String DATABASE_TABLE_LOCALLOGIN = "LocalLogin";

public static final String LOCALLOGIN_ID = "LocalLogin_id";
public static final String LOCALLOGIN_LOGIN = "Login";
public static final String LOCALLOGIN_PASSWORD = "Password";

private static final String TAG = "Debugstring";

private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static final String[] DATABASE_CREATE = {
    "CREATE Table " + DATABASE_TABLE_LOCALLOGIN + " ( "
    + LOCALLOGIN_ID + " integer PRIMARY KEY Autoincrement, "
    + LOCALLOGIN_LOGIN + " text NOT NULL, "
    + LOCALLOGIN_PASSWORD + " text NOT NULL );"};

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        for(int i = 0; i < DATABASE_CREATE.length; i++){
            Log.d(TAG,DATABASE_CREATE[i]);
            db.execSQL(DATABASE_CREATE[i]);
        }   
    }
}

public GoingOutDbAdapter(Context ctx) {
    this.mCtx = ctx;
}

public GoingOutDbAdapter open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    mDbHelper.close();
}

public Cursor fetchAllLocalLogins() {
    return mDb.query(DATABASE_TABLE_LOCALLOGIN, new String[] {LOCALLOGIN_ID, LOCALLOGIN_LOGIN, LOCALLOGIN_PASSWORD}, null, null, null, null, null);
}

}

MyActivity.java,我调用fetchAllLocalLogins

public class MyActivity extends Activity {
/** Called when the activity is first created. */   

private GoingOutDbAdapter mDbHelper;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    mDbHelper = new GoingOutDbAdapter(this);

    setContentView(R.layout.main);

Cursor localLogin = mDbHelper.fetchAllLocalLogins();

}
}

2 个答案:

答案 0 :(得分:11)

您可能希望在进行查询之前调用open()方法:

//...
mDbHelper.open(); //whitout this call mdb will be NULL
Cursor localLogin = mDbHelper.fetchAllLocalLogins();

答案 1 :(得分:1)

您应该在执行数据库操作之前打开数据库。 mDbHelper.open();