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

前端之家收集整理的这篇文章主要介绍了在SQLite数据库上执行查询时出现android NullPointerException前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试从我创建的数据库中读取数据,但在尝试获取所有记录时,我总是得到NullPointerException.

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

NullPointerException位于

return mDb.query(DATABASE_TABLE_LOCALLOGIN,new String[] {LOCALLOGIN_ID,LOCALLOGIN_LOGIN,LOCALLOGIN_PASSWORD},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,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,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();

}
}

解决方法

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

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

猜你在找的Sqlite相关文章