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.

protected void onStart() {
    firestore = FirebaseFirestore.getInstance();
            .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                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"));


public void onCreate(Bundle savedInstanceState) {

    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