how to read all value from room data base and show into recyclerview?

馋奶兔 提交于 2019-12-29 02:00:12

问题


I am using room database for storing json data from URL its working fine but while accessing data from data base to show on recyclerview its give one result at time and if i am open app second time then second object is showing, i am new in room can any one suggest me how to do this my code is. App my pojo class. My Adapter Class is.

   recyclerView = view.findViewById(R.id.recyclerView);
    postsAdapter = new PostsAdapter(new ArrayList<Example>());
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    addBorrowViewModel = ViewModelProviders.of(this).get(AddBorrowViewModel.class);
    addBorrowViewModel.getItemAndPersonList().observe(getActivity(), new Observer<List<Example>>() {
        @Override
        public void onChanged(@Nullable List<Example> itemAndPeople)
        {
            recyclerViewAdapter.addAll(itemAndPeople);
        }
    });

回答1:


Follow this or this

You didn't add LiveData in your dao. Add livedata and it will automatically return the list for you. However

In your dao

@Query("select * from table_name")
public LiveData<List<Model>> getAll();

In your activity or fragment

 yourViewModel.getAll().observe(this, new Observer<List<Model>>() {
        @Override
        public void onChanged(@Nullable List<Model> models) {
            adapter.addAll(models);
        }
    });


来源:https://stackoverflow.com/questions/52516075/how-to-read-all-value-from-room-data-base-and-show-into-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!