首页 > 解决方案 > 从 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;
    }

标签: androidsqlite

解决方案


更好的方法是使用 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;
}

推荐阅读