在Firebase数据获取方法中创建无限循环

时间:2018-07-05 06:26:29

标签: java android firebase google-cloud-firestore

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();
        }
    });
}
  

如果在失败侦听器中再次调用发生数据提取错误的方法,并且在...正确的情况下启动启动,则它在启动屏幕中起作用

2 个答案:

答案 0 :(得分:1)

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);
        }
    });
}

答案 1 :(得分:0)

您将得到一个无限循环,因为每次发生错误时,都会触发addOnFailureListener()方法,该方法就是调用fetchdata()方法。这种技巧称为recursion,但对您而言根本无法帮助您。要解决此问题,请仅处理fetchdata()并使用以下代码,而不用调用Exception方法:

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
        }
    });
}