1

I am trying to implement the MVVM pattern in my project and i have a problem with the repository. When I try to get the data from Firebase, the data variable is already set to the initial value of dataSet. The data from Firebase is fetched correctly, but it comes to late.

public class BikeRepository {
    private static BikeRepository instance;
    private ArrayList<Bike> dataSet = new ArrayList<Bike>();
    private DatabaseReference reference;
    private FirebaseUser user;

    public static BikeRepository getInstance() {
        if (instance == null) {
            instance = new BikeRepository();
        }
        return instance;
    }

    public MutableLiveData<ArrayList<Bike>> getBikes() {
        setBikes();
        MutableLiveData<ArrayList<Bike>> data = new MutableLiveData<>();
        data.setValue(dataSet);
        System.out.println(dataSet);
        return data;
    }

    private void setBikes() {
        user = FirebaseAuth.getInstance().getCurrentUser();
        String owner = user.getUid();
        reference = FirebaseDatabase.getInstance(getResources().getString(R.string.db_instance)).getReference("Users").child(owner).child("BikeCollection");

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for(DataSnapshot postSnapshot: snapshot.getChildren()){
                    Bike bike = postSnapshot.getValue(Bike.class);
                    dataSet.add(bike);
                    System.out.println(dataSet.size());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

    }
}
  • What do you mean by "comes to late"? Are you referring to [this situation](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method/47853774)? – Alex Mamo May 30 '22 at 13:57
  • @AlexMamo yes. But I want to use onChildListener or onValueEventListener, not onSingleValueEventListener like in that solution – Bogdan Colhon May 30 '22 at 14:16
  • The solution is always the same, no matter what kind of listener are you using. If you understand Kotlin, then this [article](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5) will help. – Alex Mamo May 30 '22 at 15:43

0 Answers0