gpt4 book ai didi

java - 如何使用 LiveData 对象更新 Room 数据库行?

转载 作者:行者123 更新时间:2023-12-02 09:12:24 25 4
gpt4 key购买 nike

我想同时更新我的​​用户界面和数据库条目。为此,我在代码中使用 OnChanged 观察者(下面的代码 fragment )。但是,update() 需要一个常规对象,而不是 LiveData<>。如果我更改 update() 方法以接收 LiveData,则会收到一条错误消息,指出我需要将其注释为 @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);
}
}
}
}

编辑 - 预览:

enter image description here

最佳答案

LiveData 获取值(在您的情况下:要从 UserProfile 获取 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());
}
});
}

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

关于java - 如何使用 LiveData<T> 对象更新 Room 数据库行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59303626/

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