如何在 recyclerview 顶部显示房间数据库中的最后一项

How to show the last item from room database at top in recyclerview

每当我向数据库添加新对象并尝试使用 Recyclerview 显示它们时,我都会从房间数据库中提取数据,它们出现在回收器视图的底部我没有使用 add(data,Position) 中的列表功能recyclerview 适配器,因为它复制了 recyclerview 中的数据,例如,如果数据已经存在于 recyclerview 中,并且用户尝试使用搜索视图再次搜索相同的数据,它也会被复制,我也尝试使用布局管理器反转列表,但随后它将列表滚动到 recyclerview 中的最后一项我也尝试 smoothscroll 到位置 0 但它也不起作用。 如果数据库中不存在数据,我使用搜索视图首先从数据库中搜索数据,我通过 API 从服务器获取它,将其插入数据库并通知 recyclerview 更改一切正常,除了该数据出现在底部

主要Activity代码

 private SearchView.OnQueryTextListener onQueryTextListener =
        new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (query.length() >= 3) {
                    getDealsFromDb(query);
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.length() >= 3) {
                    getDealsFromDb(newText);
                }
                return true;
            }

            private void getDealsFromDb(String searchText) {
                searchText = "%" + searchText + "%";
                final String finalSearchText = searchText;
                model.getDevicenames(searchText).observe(MainActivity.this, new Observer<List<MobileDataBaseObjectClass>>() {
                    @Override
                    public void onChanged(@Nullable List<MobileDataBaseObjectClass> mobileDataBaseObjectClasses) {
                        if (mobileDataBaseObjectClasses != null) {
                            if (mobileDataBaseObjectClasses.size() == 0) {
                                Log.i("Test", "Main Activity not found in database fetching from api: ");
                                model.insertSingleObject(finalSearchText);
                            } else {

                                mAdapter.setWords(mobileDataBaseObjectClasses);
                            }
                        }
                    }
                });

            }
        };

您必须将列表传递给适配器。首先,您从数据库中获取列表,该列表将以类似于最后一个索引的最后一项的方式排序。获取列表后,只需调用反转列表的方法。

List<DailyConsumption> mList = myDataBase.dailyConsumptionDao().findByDate(date);
Collections.reverse(mList); // inverses the list and shows last item at first index
// now pass this list to the adapter