Firebase Firestore asynchronous behavior problem

Here I'm trying to fetch user profile data from the firestore in the onStart method. onSuccess of firebase is of asynchronous behavior so the TOAST in onCreate method will produce nullpointerexception. Is there any way to delay the onCreate call until onSuccess is finished i.e. data is fetched from the firestore.

Note: I wanted to load user profile data object before the execution of onCreate method.

    @Override
protected void onStart() {
    super.onStart();
    firestore = FirebaseFirestore.getInstance();
    firestore.collection("users").document(cUserEmail).get()
            .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                @Override
                public void onSuccess(DocumentSnapshot documentSnapshot) {
                    user = new User(documentSnapshot.getString("name")
                            , documentSnapshot.getString("email")
                            , documentSnapshot.getString("rollNumber")
                            , documentSnapshot.getString("mobileNumber")
                            , documentSnapshot.getString("password")
                            , documentSnapshot.getString("department")
                            , documentSnapshot.getString("semester"));
                }
            });

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_std);
    findViews();

    Toast.makeText(this, user.getName(), Toast.LENGTH_SHORT).show();
}

1 answer

  • answered 2019-10-08 03:44 Mohammad Zaki

    I think the data you are trying to fetch is taking some time and the api call is running on thread before getting data the toast message code is called where the user is still null.

    Solution 1: Write toast message in success of data.

    Solution 2: Try to show a loading until data is fetched.

    Note: It is not a good practice fetch data in onStart