简体   繁体   中英

Creating Infinite loop in firebase data fetch method

private void fetchdata() {
    db.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            ArrayList<String> cities = (ArrayList) documentSnapshot.get("cities");
            i = new Intent(Splash.this, Select.class);
            i.putStringArrayListExtra("cities", cities);
            startActivity(i);
        }

    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {

           /*do when the cities list is not fetch  */
            fetchdata();
        }
    });
}

It works in splash screen if data fetch error occured method is called again in failure listener and splash goes on is it a ......proper way

private void fetchdata() {
    ArrayList<String> cities = new ArrayList<String>();
    i = new Intent(Splash.this, Select.class);

    db.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {

            cities = (ArrayList) documentSnapshot.get("cities");
            i.putStringArrayListExtra("cities", cities);
            startActivity(i);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {

            /* simple startActivity  */
            i.putStringArrayListExtra("cities", cities);
            startActivity(i);
        }
    });
}

You are getting an infinite loop because everytime an error occurs, the addOnFailureListener() method is triggered, which in term is calling fetchdata() method. This tehnique is called recursion , but in your case is not helping you at all. To solve this, instead of calling fetchdata() method, please just handle the Exception and use the following code:

private void fetchdata() {
    db.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            List<String> cities = (ArrayList) documentSnapshot.get("cities");
            Intent intent = new Intent(Splash.this, Select.class);
            intent.putStringArrayListExtra("cities", cities);
            startActivity(intent);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            e.printStackTrace(); //Handle Exception
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM