android - 从 MainActivity 访问数据库中的行有什么问题?
问题描述
我正在尝试以下列方式从 MainActivity 访问我的数据库中的一行。我想知道一种更好的方法来做到这一点,因为这每次都会使我的应用程序因错误而崩溃。即使在冷重启和擦除数据之后。
“23:06 模拟器:glTexImage2D:得到错误预 :( 0x502 内部 0x1908 格式 0x1908 类型 0x1401
我认为有更好的方法来做到这一点。我正在调用一个方法,该方法采用一个用户对象,该对象存储在我的数据库中大概在索引 1 处。(数据库中的第一位)
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;
}
解决方案
更好的方法是使用 Room 将数据保存在本地数据库中
这是您的代码,我看到空值检查已完成,但它仅保护一条语句免受 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;
}
推荐阅读
- php - 如何缓存 rand() 的结果?
- spark-streaming - NiFi & Spark 集成错误:java.lang.NoClassDefFoundError: org/apache/http/nio/protocol/HttpAsyncResponseConsumer
- reactjs - es6 javascript箭头函数
- kubernetes - 如何在 Kubernetes 中从 pod 运行命令到主机
- mysql - sql优化:通过子查询或自己的查询计算所有行/其他改进
- python - 从熊猫中的2个数据帧打印所有出现的映射数据
- python - 如何提高 pandas 中的 iterrows 操作速度
- c++ - 如何在 C++ 中正确设置 Lua 局部变量
- sql - 获取流程完成记录的 SQL 查询
- dbcontext - .Net Framework 4.7.2 应用程序中的 EF Core 2.1.1 DbContextPooling