frostblooded frostblooded - 5 months ago 19
Android Question

How to use Volley in Android programming and keep code clean? (callback issues)

Right now I have working code for my Android application. I use Volley, but, because of callbacks, I don't feel like my code is as clean as could be.

Two functions of my code right now are:

private void updateSettings() {
...
HTTP.requestObject(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
shiftStart = getHour(response.getString("shift_start"));
shiftEnd = getHour(response.getString("shift_end"));
} catch (JSONException e) {
Log.i(MainActivity.TAG, "JSON parse error: " + e.toString());
e.printStackTrace();
}

startCall();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
HTTP.handleError(error, getApplicationContext());
startCall();
}
}, getApplicationContext());
...
}

private void startCall() {
...
CallActivity.makeCall(getApplicationContext());
...
}


The point here is that I want to make a "call", which isn't very important, but before that I need to update my settings from the server. Of course, I need to make the call after the settings are updated, so I start the call from the Volley callback(I use HTTP.requestObject, which is a custom class that I have made, but it only adds the request to the request queue and sets a timeout). The problem is that when you call the function updateSettings() you don't really expect to start a "call" or anything like that. How can this be avoided?

P.S. I am not sure if I am explaining the issue clearly. Please ask below if you need me to clarify.

Answer

If the method is only designed to update some settings, then yes, you should enforce the single responsibility principle for that method and not make a call if it isn't meant to do that.

The way around that is to essentially copy Volleys callback parameter pattern. Have an OnSettingsUpdatedListener interface that will be passed to the method for updating settings, then invoke the methods of the listener there, which will route back to where you called it from, where you are welcome to make a call or whatever.