Search code examples
javaandroidandroid-viewmodel

How to wait till LiveData of a ViewModel is retrieved


In my android application, I have a fragment containing a view pager with two child fragments. The app uses firebase. I am attempting to run a query on the second child fragment, based on the value chosen on the first child fragment. This value is passed to the second value through a ViewModel. But when i run my application it crashes due to the following error: "java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()". How can i get my application to wait until the value is retrieved and assigned from the ViewModel

ViewModel code:

public class AppointmentBookingViewModel extends ViewModel
{
    private static MutableLiveData<String> mName = new MutableLiveData<>();

    public void setBarberSchedules(String name)
    {
        mName.setValue(name);
    }

    public static LiveData<String> getBarberSchedules()
    {
        return mName;
    }
}

First child fragment:

booktv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AppointmentBookingFragment.toNextViewpagerPage();

                        appointmentBookingViewModel.setBarberSchedules(itemRef.getKey());
                    }
                });

Second Child Fragment:

@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        appointmentBookingViewModel = new ViewModelProvider(getParentFragment()).get(AppointmentBookingViewModel.class);
        AppointmentBookingViewModel.getBarberSchedules().observe(requireActivity(), new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String s)
            {
                barberId = s;
                /*Toast toast = Toast.makeText(getActivity().getApplicationContext(), s, Toast.LENGTH_SHORT);
                toast.show();*/
            }
        });
    }

    @Override
    public void onStart()
    {
        super.onStart();
        Query query = FirebaseDatabase.getInstance().getReference().child("Users").child("Barbers").child(barberId).child("TimeSlots").child("Day 1").orderByChild("id");
// this is where the error occurs due to barberId being null when this line is executed


Solution

  • This happens because you are instantiating FirebaseDatabase while barberId isn't set yet

    Simply move this line

    Query query = FirebaseDatabase.getInstance().getReference().child("Users").child("Barbers").child(barberId).child("TimeSlots").child("Day 1").orderByChild("id");
    

    to onChanged callback

    @Override
    public void onChanged(@Nullable String s)
    {
          barberId = s;
          Query query = FirebaseDatabase.getInstance().getReference().child("Users").child("Barbers").child(barberId).child("TimeSlots").child("Day 1").orderByChild("id"); // Here
          /*Toast toast = 
          Toast.makeText(getActivity().getApplicationContext(), s, Toast.LENGTH_SHORT);
                    toast.show();*/
    }
    

    Then FirebaseDatabase process will be called after data is successfully retrieved