Java 如何使用LiveData对象更新房间数据库行?

Java 如何使用LiveData对象更新房间数据库行?,java,android,android-room,Java,Android,Android Room,我想同时更新我的UI和数据库条目。为此,我在下面的代码片段中使用了一个OnChanged观察器。但是,更新需要一个常规对象,而不是LiveData。如果我将update方法更改为接收LiveData,我会收到一个错误,说我需要将is注释为@Entity,这也不起作用。如何使用update来更新数据库中给定userProfile的单个字段 private LiveData<UserProfile> userProfile; ... protected void onCreate(@

我想同时更新我的UI和数据库条目。为此,我在下面的代码片段中使用了一个OnChanged观察器。但是,更新需要一个常规对象,而不是LiveData。如果我将update方法更改为接收LiveData,我会收到一个错误,说我需要将is注释为@Entity,这也不起作用。如何使用update来更新数据库中给定userProfile的单个字段

private LiveData<UserProfile> userProfile;

...

protected void onCreate(@Nullable Bundle savedInstanceState) {

    ...

    // Initialize the dao used to return the size of active/inactive users in the users table
    final WorksideDatabase mDb = WorksideDatabase.getInstance(this);
    userProfile = mDb.userProfileDao().getUser(id);


    userProfile.observe(
        UserServiceStatus.this,
        new Observer<UserProfile>() {
            @Override
            public void onChanged(@Nullable UserProfile sections) {

                ...

                mDb.userProfileDao().update(userProfile);
            }
        }
    }
}

编辑-预览:

在您的案例中,要从LiveData获取值:要从LiveData获取UserProfile,您需要使用getValue方法。另外,请确保在后台线程上更新

private LiveData<UserProfile> userProfile;

@Override
public void onChanged(@Nullable UserProfile sections) {
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            // Option 1: use method parameter
            mDb.userProfileDao().update(sections);

            // Option 2: get the value
            mDb.userProfileDao().update(userProfile.getValue());
        }
    });
}

我不明白为什么要编写一个从数据库中立即取回的对象,但是使用上面的解决方案,您可以做到这一点。您可能只想在更改对象后将其写回数据库。

我不太明白您想做什么。你从数据库里得到了什么,想马上写回去?!视图层不应包含对数据库的引用和对其引用的逻辑。考虑使用MVVM模式,其中您的LIFEDATA将在ViewModel中创建,它将调用一个交互逻辑层,它将与数据库、存储库数据交互。layer@MarkusPenguin我不一定要立即更新数据库-这可以在Backpress上完成。我只是不知道如何传递我使用userProfile.getValue.setStatusfalse设置的新值;到数据库行。@Steyrix好吧,老实说,这与手头的问题无关,但至少需要3倍的代码才能完成同样的事情。他不需要任何交互者来完成这个任务。@EpicPandaForce我只想让作者注意,他不应该在production.mDb.userProfileDao.updatesections中使用如此简单和不明确的方法;给出无法访问主线程上的数据库的错误,因为它可能会长时间锁定UI。我尝试运行mDb.userProfileDao.updateuserProfile.getValue;在OnBackpress中,也会出现相同的错误。我应该在哪里运行更新?或者我必须调用ViewModel对象来执行此操作吗?用户可以决定更改状态,但不是按后退,而是退出应用程序。如果新的状态值仍然保存到数据库中,这将非常理想。最简单的方法是将更新调用包装到AsyncTask中。如果您想知道为什么允许您在主线程上调用getUser:这是因为您得到了一个LiveData实例。要解决这个问题,您需要在后台线程上执行该写操作。谢谢。我在两种情况下都使用AsyncTask,切换为active/inactive,数据库也会更新,即使我选择关闭应用程序并返回,这也是我最初想要的。