首页 > 解决方案 > 在 RecyclerView 中显示数据时,来自 SQLite 的数据序列发生了变化

问题描述

我已将数据存储在SQLite数据库中。我需要从数据库中显示该数据RecyclerView。但是第一次在 RecyclerView 中检索和显示数据时,它会在存储在数据库中的序列中检索并在 Recyclerview 上设置。当我尝试从数据库中获取相同的数据并在 RecyclerView 上设置时它会自动更改顺序。
这是从SQLite数据库中检索数据的代码

public ArrayList<ReservationEntry> getDbReservation(){
        SQLiteDatabase db = this.getWritableDatabase();
        String query="SELECT * FROM "+ RESERVATIONS;
        Cursor c=db.rawQuery(query,null,null);
        ArrayList<ReservationEntry> reserveList=new ArrayList<>();
        if(c.moveToFirst()){
            do{
                ReservationEntry entry=new ReservationEntry();
                entry.setName(c.getString(0));
                entry.setNoOfPeople(c.getString(1));
                entry.setTime(c.getString(2));
                entry.setDate(c.getString(3));
                entry.setBirthday(c.getString(4));
                entry.setAniversary(c.getString(5));
                reserveList.add(entry);
            }while (c.moveToNext());
        }
        return reserveList;

    }  

这是要设置的代码RecyclerViewAdapter

private void readDatabaseReservation(final ArrayList<ReservationEntry> dbList) {
        adapter=newReservationAdapter(dbList,getActivity().getApplicationContext());
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
}  

如何解决这个问题?

标签: androiddatabaseandroid-recyclerviewandroid-sqlite

解决方案


您必须添加您的适配器此函数来更改数据并调用 notifyDataSetChanged。

所以把它添加到你的适配器

public void setData(ArrayList<ReservationEntry> dbList){
  this.yourListData = dbList;
  notifyDataSetChanged();
}

并像这样使用它

private void readDatabaseReservation(final ArrayList<ReservationEntry> dbList) {
    adapter.setData(dbList);
} 

希望有帮助。更多添加您的适配器代码


推荐阅读