4

我正在尝试从我创建的数据库中读取数据,但在尝试获取所有记录时总是会收到 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();

}
}
4

2 回答 2

11

open()在进行查询之前,您可能需要调用该方法:

//...
mDbHelper.open(); //whitout this call mdb will be NULL
Cursor localLogin = mDbHelper.fetchAllLocalLogins();
于 2012-04-09T09:10:05.447 回答
1

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

于 2012-04-09T09:40:25.190 回答