Performance 将DiffUtil与LIveData+;房间数据库?

Performance 将DiffUtil与LIveData+;房间数据库?,performance,android-recyclerview,android-room,android-livedata,Performance,Android Recyclerview,Android Room,Android Livedata,我正在将房间数据库与LiveData一起使用,但是我的本地数据库按照我们的要求更新得太快,同时我必须重新加载我的回收器视图。我没有调用notifyDataSetChanged()到适配器,而是尝试使用DiffUtil,但正在崩溃或无法正确重新加载,这是不确定的。 我将学习本教程: MyAdapter: public class SwitchGridAdapter extends RecyclerView.Adapter<SwitchGridAdapter.ViewHolder> {

我正在将
房间数据库
LiveData
一起使用,但是我的本地数据库按照我们的要求更新得太快,同时我必须重新加载我的回收器视图。我没有调用
notifyDataSetChanged()
到适配器,而是尝试使用
DiffUtil
,但正在崩溃或无法正确重新加载,这是不确定的。 我将学习本教程:

MyAdapter:

public class SwitchGridAdapter extends RecyclerView.Adapter<SwitchGridAdapter.ViewHolder> {


    private  List<Object> allItemsList;

    private LayoutInflater mInflater;
    private OnItemClickListener mClickListener;
    private  Context context;

    private Queue<List<Object>> pendingUpdates =
            new ArrayDeque<>();

    // data is passed into the constructor
  public SwitchGridAdapter(Context context,List<Appliance> applianceList,List<ZmoteRemote> zmoteRemoteList) {
        this.mInflater = LayoutInflater.from(context);
         this.context = context;

       allItemsList = new ArrayList<>();
        if (applianceList!=null) allItemsList.addAll(applianceList);
        if (zmoteRemoteList!=null)allItemsList.addAll(zmoteRemoteList);

    }

    // inflates the cell layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R .layout.switch_grid_item, parent, false);

        return new ViewHolder(view);
    }


    // binds the data to the textview in each cell
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
     // Doing some update with UI Elements
    }

    // total number of cells
    @Override
    public int getItemCount() {
        return allItemsList.size();
    }

    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnLongClickListener {
        TextView myTextView;
        ImageView imgSwitch;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = (TextView) itemView.findViewById(R.id.txtSwitchName);
            imgSwitch = (ImageView) itemView.findViewById(R.id.imgSwitchStatus);

            itemView.setOnClickListener(this);

            itemView.setOnLongClickListener(this);

        }

        @Override
        public void onClick(View view) {
           // handling click 
        }

        @Override
        public boolean onLongClick(View view) {
           return true;
    }

    // convenience method for getting data at click position
    Object getItem(int id) {
        return allItemsList.get(id);
    }

    // allows clicks events to be caught
   public void setClickListener(OnItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface OnItemClickListener {
        void onItemClick(View view, int position);
        void onItemLongPressListner(View view, int position);
    }



// ✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
// From This Line Reloading with Diff Util is Done .
//✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅


    public  void  setApplianceList( List<Appliance> applianceList,List<ZmoteRemote> zmoteRemoteList)
    {

        if (allItemsList == null)
            allItemsList = new ArrayList<>();

        List<Object> newAppliances = new ArrayList<>();
        if (applianceList!=null) newAppliances.addAll(applianceList);

        updateItems(newAppliances);

    }


    // when new data becomes available
    public void updateItems(final List<Object> newItems) {
        pendingUpdates.add(newItems);
        if (pendingUpdates.size() > 1) {
            return;
        }
        updateItemsInternal(newItems);
    }
    // This method does the heavy lifting of
    // pushing the work to the background thread
    void updateItemsInternal(final List<Object> newItems) {
        final List<Object> oldItems = new ArrayList<>(this.allItemsList);
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final DiffUtil.DiffResult diffResult =
                        DiffUtil.calculateDiff(new DiffUtilHelper(oldItems, newItems));
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        applyDiffResult(newItems, diffResult);
                    }
                });
            }
        }).start();
    }
    // This method is called when the background work is done
    protected void applyDiffResult(List<Object> newItems,
                                   DiffUtil.DiffResult diffResult) {
        dispatchUpdates(newItems, diffResult);
    }
    // This method does the work of actually updating
    // the backing data and notifying the adapter
    protected void dispatchUpdates(List<Object> newItems,
                                   DiffUtil.DiffResult diffResult) {


            // ❌❌❌❌❌❌ Next Line is Crashing the app ❌❌❌❌❌
            pendingUpdates.remove();

            dispatchUpdates(newItems, diffResult);
            if (pendingUpdates.size() > 0) {
                updateItemsInternal(pendingUpdates.peek());
            }
    }

}
公共类SwitchGridAdapter扩展了RecyclerView.Adapter{
私人名单联合名单;
私人停车场;
私有的mClickListener mClickListener;
私人语境;
私有队列挂起更新=
新ArrayDeque();
//数据被传递到构造函数中
公共SwitchGridAdapter(上下文上下文、列表applianceList、列表zmoteRemoteList){
this.mInflater=LayoutInflater.from(上下文);
this.context=上下文;
allItemsList=新的ArrayList();
如果(applianceList!=null)allItemsList.addAll(applianceList);
如果(zmotemotelist!=null)allItemsList.addAll(zmotemotelist);
}
//根据需要从xml展开单元格布局
@凌驾
public ViewHolder onCreateViewHolder(视图组父级,int-viewType){
视图=mInflater.flate(R.layout.switch\u grid\u项,父项,false);
返回新的ViewHolder(视图);
}
//将数据绑定到每个单元格中的textview
@凌驾
公共无效onBindViewHolder(ViewHolder,int位置){
//使用UI元素进行一些更新
}
//细胞总数
@凌驾
public int getItemCount(){
返回allItemsList.size();
}
//在屏幕外滚动视图时存储和回收视图
公共类ViewHolder扩展了RecyclerView.ViewHolder实现了View.OnClickListener、View.OnLongClickListener{
文本视图myTextView;
图像视图img开关;
ViewHolder(视图项视图){
超级(项目视图);
myTextView=(TextView)itemView.findViewById(R.id.txtSwitchName);
imgSwitch=(ImageView)itemView.findViewById(R.id.imgSwitchStatus);
setOnClickListener(这个);
setOnLongClickListener(此);
}
@凌驾
公共void onClick(视图){
//处理点击
}
@凌驾
仅长按公共布尔值(视图){
返回true;
}
//在点击位置获取数据的简便方法
对象getItem(int id){
返回allItemsList.get(id);
}
//允许捕获单击事件
public void setClickListener(OnItemClickListener项ClickListener){
this.mClickListener=itemClickListener;
}
//父活动将实现此方法以响应单击事件
公共接口侦听器{
void onItemClick(视图,int位置);
void onItemLongPressListner(视图,int位置);
}
// ✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
//从此行开始,使用Diff Util重新加载。
//✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
public void setApplianceList(列表applianceList、列表zmoteRemoteList)
{
如果(allItemsList==null)
allItemsList=新的ArrayList();
List newAppliances=newArrayList();
如果(applianceList!=null)newAppliances.addAll(applianceList);
更新项目(新设备);
}
//当新数据可用时
公共无效更新项(最终列表新项){
待更新。添加(新项目);
如果(pendingUpdates.size()>1){
返回;
}
更新项目内部(新项目);
}
//这种方法不需要搬运重物
//将工作推送到后台线程
void updateItemsInternal(最终列表newItems){
最终列表oldItems=new ArrayList(this.allItemsList);
最终处理程序=新处理程序();
新线程(newrunnable()){
@凌驾
公开募捐{
最终DiffUtil.DiffResult衍射结果=
DiffUtil.calculateDiff(新的DiffUtilHelper(旧项,新项));
handler.post(新的Runnable(){
@凌驾
公开募捐{
applyDiffResult(新项、衍射结果);
}
});
}
}).start();
}
//后台工作完成时调用此方法
受保护的无效applyDiffResult(列出新项,
DiffUtil.differsult(衍射结果){
DispatchUpdate(新项目、衍射结果);
}
//此方法执行实际更新的工作
//备份数据并通知适配器
受保护的无效DispatchUpdate(列出新项目,
DiffUtil.differsult(衍射结果){
// ❌❌❌❌❌❌ 下一行是应用程序崩溃❌❌❌❌❌
pendingUpdates.remove();
DispatchUpdate(新项目、衍射结果);
如果(pendingUpdates.size()>0){
updateItemsInternal(pendingUpdates.peek());
}
}
}
观察现场数据

 public  void setUpAppliancesListLiveData()
    {

        if (applianceObserver!=null)
        {
            applianceObserver  = null;
        }


        Log.e("Appliance Fetch","RoomName:"+this.roomName);

      applianceObserver =  new Observer<List<Appliance>>() {
            @Override
            public void onChanged(@Nullable List<Appliance> applianceEntities) {
                // Log.e("Appliance Result","Appliance List \n\n:"+applianceEntities.toString());

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        List<Appliance> applianceListTemp =  applianceEntities;

                        zmoteRemoteList =  new ArrayList<>();  //appDelegate.getDatabase().zmoteRemoteDao().getRemoteList(roomName);

                        // Sort according to name

                        Collections.sort(applianceListTemp, new Comparator<Appliance>() {
                            @Override
                            public int compare(Appliance item, Appliance t1) {
                                String s1 = item.getSwitchName();
                                String s2 = t1.getSwitchName();
                                return s1.compareToIgnoreCase(s2);
                            }

                        });


                        if(getActivity()!=null) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    applianceList = applianceListTemp;
                                    mRecyclerView.getRecycledViewPool().clear();
                                    adapter.setApplianceList(applianceList,zmoteRemoteList);
                                }
                            });

                        }

                    }
                }).start();
            }
        };



        appDelegate.getDatabase().applianceDao().getApplinaceListByRoomName(this.roomName).observe(this, applianceObserver);

    }
public void setUpAppliancesListLiveData()
{
if(applianceObserver!=null)
{
applianceObserver=null;
}
Log.e(“设备获取”、“RoomName:+this.RoomName”);
applianceObserver=新的观察者(){
@凌驾
更改后的公共无效(@Nullable List appliancentities){
//Log.e(“设备结果”、“设备列表”\n\n:“+applianceEntities.toString());
新线程(newrunnable()){
@凌驾
公开募捐{
列表applianceListTemp=applianceEntities;