如何将数据从 DataSnapshot 插入到 LiveData<List<Model>>?

问题描述

我需要将从 firebase 获得的数据插入到 LiveData,我不知道该怎么做

public LiveData<List<Medicationviewmodel>> getAllMeds(){

        mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
             LiveData<List<Medicationviewmodel>> medics; //Return this 
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for(DataSnapshot ds : dataSnapshot.getChildren()) {

                            Medicationviewmodel medic = ds.getValue(Medicationviewmodel.class);
                            Log.d("TAG",medic.getMedname());
                             //Todo
                        }

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
    }

解决方法

你应该把你的问题分成几个步骤:

  1. 返回实时数据:如果你想要一个实时数据,这意味着你希望有人观察它,所以我建议只拥有一个实时数据并将它返回给任何想要观察的人

    //=======Observer Activity/Fragment=============:
    final Observer<List<MedicationViewModel>> medsObserver = new Observer<List<MedicationViewModel>>() {
        @Override
        public void onChanged(@Nullable final List<MedicationViewModel> medsList) {
            // Do what you need when the new list arrives
        }
    };
    yourObject.getAllMeds().observe(context,medsObserver) //setting the observer
    //===============Your class============
    private final MutableLiveData<List<MedicationViewModel>> allMedsLiveData = new MutableLiveData<>();
    //...
    public LiveData<List<MedicationViewModel>> getAllMeds(){
       return allMedsLiveData; //returning the liveData
    }
    
  2. 填充来自 firebase 的数据:

    //===============Your class============
    private final MutableLiveData<List<MedicationViewModel>> allMedsLiveData = new MutableLiveData<>(); //the same one as the step 1
    private final List<MedicationViewModel> allMedsList = new ArrayList<>();
    //...
    private void setUpListener() {
       mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot ds : dataSnapshot.getChildren()) {
    
                        MedicationViewModel medic = ds.getValue(MedicationViewModel.class);
                        Log.d("TAG",medic.getMedName());
                        allMedsList.add(medic); // or update if exists (just adding to keep things simple,but you get the idea)
                    }
                    allMedsLiveData.postValue(allMedsList) //Using postvalue here in case the DB is fetching data on a worker thread,as it should. This call will launch the "medsObserver" observer on the observer activity/fragment on step 1
    
                }
    
                @Override
                public void onCancelled(DatabaseError databaseError) {
    
                }
            });
     }
    

希望它对你有用!