[英]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. 由于每次发生错误时, addOnFailureListener()
触发addOnFailureListener()
方法,这就是调用fetchdata()
方法,从而导致无限循环。 This tehnique is called recursion
, but in your case is not helping you at all. 这种技术称为recursion
,但在您的情况下根本无法帮助您。 To solve this, instead of calling fetchdata()
method, please just handle the Exception
and use the following code: 要解决此问题,请仅处理Exception
并使用以下代码,而不是调用fetchdata()
方法:
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
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.