Android 从MainActivity访问数据库中的行有什么问题?
我正试图以以下方式从MainActivity访问数据库中的一行。我想知道一个更好的方法来做到这一点,因为这使我的应用程序崩溃,每次都有错误。即使在冷重启和擦除数据之后 23:06 Emulator:glTexImage2D:Get err pre:0x502内部0x1908格式0x1908类型0x1401 我想有更好的方法来做到这一点。我正在调用一个方法,该方法获取一个存储在我的数据库中的用户对象(可能位于索引1处)。数据库第一名Android 从MainActivity访问数据库中的行有什么问题?,android,sqlite,Android,Sqlite,我正试图以以下方式从MainActivity访问数据库中的一行。我想知道一个更好的方法来做到这一点,因为这使我的应用程序崩溃,每次都有错误。即使在冷重启和擦除数据之后 23:06 Emulator:glTexImage2D:Get err pre:0x502内部0x1908格式0x1908类型0x1401 我想有更好的方法来做到这一点。我正在调用一个方法,该方法获取一个存储在我的数据库中的用户对象(可能位于索引1处)。数据库第一名 if(myDb.isNotEmpty() == true) {
if(myDb.isNotEmpty() == true) {
MyProgress.calculateBalance***(myDb.getUser(1));***
这是我的getUser方法
public User getUser(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
if (cursor != null)
cursor.moveToFirst();
User user = new User();
user.setId(Integer.parseInt(cursor.getString(0)));
user.setWeight (Integer.parseInt(cursor.getString(1)));
user.setAge(Integer.parseInt(cursor.getString(2)));
return user;
}
方法的最后一部分应如下所示:
if ((cursor != null) && (cursor.moveToFirst()) {
User user = new User();
user.setId(Integer.parseInt(cursor.getString(0)));
user.setWeight (Integer.parseInt(cursor.getString(1)));
user.setAge(Integer.parseInt(cursor.getString(2)));
return user;
} else {
return null;
}
此代码确保,如果返回的游标为null或不包含至少1行,则不会引发错误。
在这种情况下,该方法将返回null。
当然,如果游标准备时没有错误,并且myDB已正确初始化,那么游标没有理由为null,因此必须检查有效的列、表和数据库名称。
此外,每次对其中任何一个进行更改后,请始终从仿真器/设备卸载应用程序,以便删除数据库并重新运行应用程序以重新创建所有内容 更好的方法是使用
这是您的代码,我看到空检查已经完成,但它只保护一条来自NPE的语句。您需要在此if条件下包装用户创建
@Nullable
public User getUser(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
if (cursor != null && cursor.moveToFirst()) {
User user = new User();
user.setId(Integer.parseInt(cursor.getString(0)));
user.setWeight (Integer.parseInt(cursor.getString(1)));
user.setAge(Integer.parseInt(cursor.getString(2)));
return user;
}
return null;
}
此崩溃我的应用程序不是错误描述;请添加相关的堆栈跟踪。。。此外,建议调用db.close甚至可能是崩溃的原因。该错误消息与GL驱动程序相关。。。与代码无关。相关的堆栈跟踪应该引用MainActivity并有一组行;通常以红色文本显示。除此之外,我真的找不到其他错误消息。然而,问题已经解决了。自从我包装了getUser方法后,它就开始工作了。您是说我应该在MainActivity中调用db.close吗?请注意,查询总是返回游标或抛出错误。因此,将代码包装在try..catch块中,然后忘记ifcursor!=无效的还请注意,如果返回了有效的游标对象,这并不意味着您有任何值。这意味着您应该先检查cursor.moveToFirst返回的布尔值,然后再继续尝试读取这些值。