Firestore更新后,LiveData无法刷新RecyclerView

时间:2019-02-25 00:25:45

标签: android firebase android-recyclerview google-cloud-firestore

我有一个使用Firestore作为其数据库的Android应用。我遵循了这一系列博客文章,以在我的应用https://firebase.googleblog.com/2017/12/using-android-architecture-components.html中设置我的firestore数据库,然后按照以下stackoverflow条目更改了我的代码以适用于firestore:Android Architecture Components with Firebase specifically Firestore

此后,我成功地在回收站视图中显示了查询结果,但是,当我在应用程序中添加了交换以进行更新(我通过将isActive标志设置为false进行软删除)操作时,LiveData在刷新RecyclerView。这是我的代码段:

MainActivity.java

  TaskViewModel viewModel = 
ViewModelProviders.of(this).get(TaskViewModel.class);

    LiveData<LinkedList<TaskProperties>> liveData = viewModel.getTaskPropertiesLiveData();

    final MainActivity mainActivityReference =  this;

    liveData.observe(this, new Observer<LinkedList<TaskProperties>>() {
        @Override
        public void onChanged(@Nullable LinkedList<TaskProperties> taskProperties) {
            if (taskProperties != null) {

                // Get a handle to the RecyclerView.
                mRecyclerView = findViewById(R.id.recyclerview);
                // Create an adapter and supply the data to be displayed.
                mAdapter = new TaskListAdapter(mainActivityReference, taskProperties);
                // Connect the adapter with the RecyclerView.
                ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(mAdapter);

                ItemTouchHelper touchHelper = new ItemTouchHelper(callback);

                touchHelper.attachToRecyclerView(mRecyclerView);

                mRecyclerView.setAdapter(mAdapter);
                // Give the RecyclerView a default layout manager.
                mRecyclerView.setLayoutManager(new LinearLayoutManager(mainActivityReference));
            }
        }
    });

查看模型:

public class TaskViewModel extends ViewModel {
    private LinkedList<TaskProperties> taskProperties;
    private static final Query PROJECT_REF = FirebaseFirestore.getInstance().collection("project").whereEqualTo("active", true);

    private final FirebaseQueryLiveData liveData = new FirebaseQueryLiveData(PROJECT_REF);

       public TaskViewModel() {
      taskPropertiesLiveData.addSource(liveData, new Observer<QuerySnapshot>() {
            @Override
                public void onChanged(@Nullable final QuerySnapshot querySnapshot) {
                if (querySnapshot != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            taskProperties =  new LinkedList<TaskProperties>();
                            for (DocumentSnapshot document : querySnapshot.getDocuments()) {
                                taskProperties.addLast(document.toObject(TaskProperties.class));

                            }

                            taskPropertiesLiveData.postValue(taskProperties);
                        }
                    }).start();
                } else {
                    taskPropertiesLiveData.setValue(null);
                }
            }
        });
    }

    @NonNull
    public LiveData<LinkedList<TaskProperties>> getTaskPropertiesLiveData() {
        return taskPropertiesLiveData;
    }
}

要删除的回调类中的代码:

 public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
    }

适配器中的构造函数:-

  public TaskListAdapter(Context context,LinkedList<TaskProperties> taskList) {
        mInflater = LayoutInflater.from(context);
        this.taskList = taskList;
    }

适配器中要删除的代码:-

  public void onItemDismiss(int position) {

        TaskDao taskDao = new TaskDao();
        taskDao.softDeleteTaskInDB(taskList.get(position));
    }

DAO类中的代码以进行更新(软删除):-

public void softDeleteTaskInDB(TaskProperties taskProperties){

    taskProperties.setActive(false);
    database.collection("project")
            .document(taskProperties.getTask())
            .set(taskProperties).
            addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Log.d(DEBUG_TAG, "DocumentSnapshot successfully written!");
                        }
                    })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(DEBUG_TAG, "Error writing document", e);
                }
            });

    Log.i(DEBUG_TAG,taskProperties.getTask());

}

我观察到,当我从列表末尾删除一个组件时,LiveData能够刷新视图,但是当我从列表中间删除时,视图有时无法正确刷新。从日志中,我发现传递到适配器类的位置工作正常,但是tasklist数组没有最新值。

例如,如果任务列表包含:-

  • 鼠标
  • 兔子
  • 老虎

,如果先后连续删除Mouse和Rabbit,则在两种情况下适配器类的onItemDismiss都位于位置3,但是Adapter类中的taskList变量仍在位置3包含Mouse。这意味着LiveData可能没有刷新RecyclerView。

有人可以告诉我我要去哪里错吗?

谢谢, 桑浩

0 个答案:

没有答案