简体   繁体   English

如何通过cursorAdapter使用新的系统架构ViewModel / LiveData?

[英]How to make use of the new system architecture ViewModel/LiveData with cursorAdapter?

While learning the new android Architecture component's ViewModel and LiveData, having a little confusion when observe the LiveData changing from database source change, and how this would work with Cursor adapter. 在学习新的Android Architecture组件的ViewModel和LiveData时,当观察LiveData从数据库源更改的变化以及如何与Cursor适配器一起使用时,会有些困惑。

in https://developer.android.com/reference/android/widget/CursorAdapter.html , it says https://developer.android.com/reference/android/widget/CursorAdapter.html中 ,它说

int FLAG_REGISTER_CONTENT_OBSERVER
If set the adapter will register a content observer on the cursor 
and will call onContentChanged() when a notification comes in. Be 
careful    when using this flag: you will need to unset the current 
Cursor from the adapter to avoid leaks due to its registered 
observers. This flag is not needed when using a CursorAdapter 
with a CursorLoader.

so the with cursorAdaptor it has a way to get the 'live update' when the database data is updated. 因此,使用cursorAdaptor可以在数据库数据更新时获取“实时更新”。

is there a way to use the LiveData (to observe the database data update) with the cursorAdaptor? 有没有办法使用带有cursorAdaptor的LiveData(观察数据库数据更新)?

trying to show the question of where to use the liveData updating the cursor in snippet below: (with the sample of https://codelabs.developers.google.com/codelabs/android-persistence ) 尝试显示在哪里使用liveData更新下面代码段中的光标的问题:(使用https://codelabs.developers.google.com/codelabs/android-persistence示例)

the Book: 书:

@Entity
public class Book {
    public @PrimaryKey String id;
    public String title;
}

The ViewModel: ViewModel:

public class BooksBorrowedByUserViewModel extends AndroidViewModel {

public final LiveData<List<Book>> books;

private AppDatabase mDb;

public BooksBorrowedByUserViewModel(Application application) {
    super(application);
    createDb();
    // Books is a LiveData object so updates are observed.
    books = mDb.bookModel().findBooksBorrowedByName("Mike");   //<=== this ViewModel specific to one type query statement
}

public void createDb() {
    mDb = AppDatabase.getInMemoryDatabase(this.getApplication());

    // Populate it with initial data
    DatabaseInitializer.populateAsync(mDb);
}
}

is this the way to use LiveData observer to force reload cursor? 这是使用LiveData观察器强制重新加载游标的方法吗?

private CursorAdapter listAdapter;
private BooksBorrowedByUserViewModel mViewModel;

private void subscribeUiBooks() {
    mViewModel.books.observe(this, new Observer<List<Book>>() {
        @Override
        public void onChanged(@NonNull final List<Book> books) {

            showBooksInUi(books, mBooksTextView); //<== the sample’s code

            // if would like to update the cursorAdaptor
            //
            // ??? to requery the database and swap cursor here?
            // Cursor data = queryData(buildSqlStatement());  // build the same sql statement as used in the BooksBorrowedByUserViewModel
            // listAdapter.swapCursor(data)

        }
    });
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //having a list using CursorAdaptor
    ListView list = getListView();
    listAdapter = new CursorAdapter(getActivity(), null, 0)
    list.setAdapter(listAdapter);

    // Get a reference to the ViewModel for this screen.
    mViewModel = ViewModelProviders.of(this).get(BooksBorrowedByUserViewModel.class);

    subscribeUiBooks();
}

CursorAdapter is an old stuff, you should use Room + LiveData + RecyclerView. CursorAdapter是一个旧东西,您应该使用Room + LiveData + RecyclerView。

Your data layer: 您的数据层:

public LiveData<List<UserEntity>> getUsers() {
    return userDao.getUsers();
}

Your activity: 您的活动:

viewModel.getUsers().observe(this, new Observer<List<UserEntity>>() {
    @Override
    public void onChanged(@Nullable List<UserEntity> users) {
        if (users != null) {
            adapter.setUsers(users);
        }
    }
});

In adapter: 在适配器中:

private List<UserEntity> users = new ArrayList<>();

public void setUsers(List<UserEntity> users) {
    this.users.clear();
    this.users.addAll(users);
    notifyDataSetChanged();
}

So when your activity lunch you should get live data from Room and subscribe to it. 因此,当您的活动午餐时,您应该从Room获取实时数据并进行订阅。 After that when you add something to that table, room automatically update observers, so you should just setup new data to the adapter and notify it. 之后,当您向该表中添加某些内容时,Room会自动更新观察者,因此您只需将新数据设置到适配器并通知它。

Guide to App Architecture 应用架构指南

LiveData 实时数据

Room 房间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 MVVM 架构中使用 livedata - How to use livedata in an MVVM architecture BoundService + LiveData + ViewModel 新Android推荐架构最佳实践 - BoundService + LiveData + ViewModel best practice in new Android recommended architecture 谁能解释在Android中实现MVVM架构时如何使用ViewModel和LiveData - Can any one explain how to use ViewModel and LiveData while implementing MVVM architecture in android Android体系结构组件:如何通过ViewModel观察存储库中的LiveData - Android Architecture Components: How is LiveData in the repository observed by a ViewModel 如何将WearableActivity与LiveData和ViewModel结合使用 - How can I use WearableActivity with LiveData and ViewModel 如何在多个Activity中使用ViewModel和LiveData观察器? - How use a ViewModel & LiveData observer in multiple Activity? 如何将 livedata 和 viewmodel 与 Viewholder 作为生命周期所有者一起使用? - How to use livedata and viewmodel with a viewholder as Lifecycle Owner? 如何在 Room 中将 SearchView 与 LiveData 和 ViewModel 一起使用 - How to use SearchView with LiveData and ViewModel in Room 如何使用rxjava在存储库中提出改造请求,并使用LiveData将其传递给ViewModel? - How do i use rxjava to make a retrofit request in a repository and pass it to a ViewModel using LiveData? Viewmodel观察LiveData - 怎么样? - Viewmodel observing LiveData - how?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM