Reputation: 7456
I'm using Volley for Android. I have a ListView in a fragment. If this ListView is empty (only possible if the connection failed/no internet/etc.), I want to send a GET request to the server for the data, then populate the ListView accordingly if it succeeds. If the call failed, I want to call it again in 5 minutes. This goes on until it succeeds.
What is the best way to achieve this? I'm new to Android development. I read about Services, but IDK if that is overkill.
Upvotes: 0
Views: 1403
Reputation: 614
You could use ScheduledExecutorService to manage and schedule your request. Take a look at:
Upvotes: 2
Reputation: 1491
I use to have a layer to define all my calls to services. Lets say ServiceLayer.java for example.
You could define a Handler as a global variable. (You will need to create the ServiceLayer in the MainThread). And then manage the error in the service call making the handler recall the service in 5 minutes. Something like this
public class ServiceLayer {
Handler handler = new Handler();
...
public void callToService(final String parameter,final String moreParameters,final Callback callbackDefinedByYou){
StringRequest req = new StringRequest(Method.GET, url, new Response.Listener<String>(){
@Override
public void onResponse(String s) {
//Do whatever you need, populate listviews etc
callbackDefinedByYou.populateListView(s);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//Manage the error and recall again this service
callbackDefinedByYou.onError(volleyError);
handler.postDelayed(new Runnable() {
public void run(){
callToService(parameter, moreParameter, callbackDefinedByYou);
}
}, 300000); //5 minutes
}
});
VolleyHelper.addRequestToQueue(req);
}
In this code, everytime service fails a recall is made but, in some cases you should stop doing net calls. For example when you detect there is no internet conexion, and let the user refresh screen
Upvotes: 1