gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:30:41 25 4
gpt4 key购买 nike

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

}
}

最佳答案

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

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

关于在 SQLite 数据库上执行查询时出现 android NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10071074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com