[英]How to wait till LiveData of a ViewModel is retrieved
在我的 android 应用程序中,我有一个片段,其中包含一个带有两个子片段的视图寻呼机。 该应用程序使用 firebase。 我正在尝试根据在第一个子片段上选择的值对第二个子片段运行查询。 该值通过 ViewModel 传递给第二个值。 但是当我运行我的应用程序时,它由于以下错误而崩溃:“java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()”。 如何让我的应用程序等到从 ViewModel 检索和分配值
视图模型代码:
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;
}
}
第一个子片段:
booktv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AppointmentBookingFragment.toNextViewpagerPage();
appointmentBookingViewModel.setBarberSchedules(itemRef.getKey());
}
});
第二个孩子片段:
@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
发生这种情况是因为您正在实例化FirebaseDatabase
而barberId
尚未设置
只需移动这条线
Query query = FirebaseDatabase.getInstance().getReference().child("Users").child("Barbers").child(barberId).child("TimeSlots").child("Day 1").orderByChild("id");
到onChanged
回调
@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();*/
}
然后在成功检索数据后会调用FirebaseDatabase
进程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.