4

lately I'm using Volley library in android.. It works fine but I was wondering about the most efficient way of updating the UI.. I have a Utils class that has all the Volley methods.. right now I pass all the Views that will be updated as parameters, but I've read that I could implement the listeners in my activity then pass them as parameters in the Utils class..

So my question is:

Which is more efficient and why updating the UI like this:

public void getSettings(final TextView exampleView) {
    JsonObjectRequest jsonRequest = new JsonObjectRequest(Method.GET,
            url, (String) null, new Response.Listener<JSONObject>() {
                public void onResponse(JSONObject response) {
                    try {
                        final String setting = getSettingFromJSON(response);
                        exampleView.setText(setting);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                public void onErrorResponse(VolleyError arg0) {

                }
            });

    app.add(jsonRequest);
}

Or I declare the listeners in my activity like this :

    Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
        public void onResponse(JSONObject response) {
            String setting = Utils.getSettingFromJSON(response);
            exampleView.setText(setting);
        }
    };

then I pass them into my utils function as parameters so the call would be like this :

utils.getSettings(listener);

instead of :

utils.getSettings(exampleView);

Thanks In Advance :)

Muhammad Ashraf
  • 1,252
  • 1
  • 14
  • 32

2 Answers2

0

Why not use something like EventBus to manage passing back info from the request to your activity? This way you can separate your networking code from your activities/views. The basic idea using EventBus and Volley is the following:

  • Register a class to receive some type of event, in this case probably the activity
  • Create a method in this class to handle this event, exampleView.setText(setting).
  • Post the event to the bus, post the String or volley error in the Volley listeners.

For a more detailed example checkout this blogpost or Eventbus' github page.

0

As in my question Android/Java: how to delay return in a method

I also use interface listener, however, I update views in main thread, not in Utils class

Community
  • 1
  • 1
BNK
  • 23,994
  • 8
  • 77
  • 87