加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-12 18:59:38 所属栏目:百科 来源:网络整理
导读:我正在尝试从我创建的数据库中读取数据,但在尝试获取所有记录时,我总是得到NullPointerException. 我几乎从我运行完美的另一个应用程序中复制了代码,但不知怎的,我在这里做错了. NullPointerException位于 return mDb.query(DATABASE_TABLE_LOCALLOGIN,new S
我正在尝试从我创建的数据库中读取数据,但在尝试获取所有记录时,我总是得到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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读