Android Volley: Static vs Object
Asked Answered
M

2

2

I am a junior android developer and I almost finished the alpha version of my first big project. I think that I have good knowledge of java but I am not sure if I organized my app right.

Short description: I use in my app the volley library to send and receive data from server. Because of that I created a class to manage server methods. In that class I created a lot of static methods for every connection to server I need(like this example):

public static void sendDataToServer(final Context context, final String data) {
    StringRequest mStringRequest = new StringRequest(Request.Method.POST, URL_VERIFY, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // get response
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
           // get error response
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            // the POST parameters:
            params.put(API_KEY, API_KEY_VALUE);
            params.put(API_KEY_DATA, data);
            return params;
        }
    };

    Volley.newRequestQueue(context).add(mStringRequest);
}

So in my activities I call this like MyServerClass.sendDataToServer(...)

My question is: Is it ok to call my server methods like that? Or should I make them instance methods and instantiate MyServerClass when activity is started? I must mention that I have about 5 methods in that class.

I have another class like that with methods to check data accuracy. Should I also make them instance methods and instantiate it in the activities I need?

Any reference or advice is welcome. Thanks in advance!

Machicolate answered 13/9, 2015 at 16:5 Comment(0)
Z
1

No, in your case, both ways will have the same result...

The only thing to mention is, that if you need to receive the response to your request too (may be in the future), you will need to add a Delegate / Callback / Interface to your class, to get the result right back to your calling activity instance... In that case it would be better to create a "non-static instance method" way... But you can add a non-static Method to your Class too so I don't see anything against it.

UPDATE TO COMMENT

Well for example, if you want to provide a ListView with Images... In most cases you first request an JSONArray with your ListView entries, which contains the links to Bitmaps located on the remote Server...

If you download Images Async and put them into the ImageViews in the rows of a ListView (while the user scrolls), it could be possible that images are loaded longer and the ListView will show images in wrong places... For something like that you will need a Singleton Pattern, which will manage the downloads for you... This will not be possible with your class/static Method

Zaller answered 13/9, 2015 at 16:42 Comment(4)
Right now I assume that I receive a response from server(JSON that I need in my app), because I send nothing to server before checking if internet connection is active. But your Callback idea is a better one. I have a lot to learn. Thanks for your answer! I will accept your answer as the correct one if there will be no other answer to analyze in three days.Machicolate
I think that you need to get the request all the time, because you need to know if data was sent successfully. In my example I have a guy working on the server side and I receive a JSON with OK message if everything arrived correctly, and a negative response otherwise.Machicolate
Thats true... I just answered your question, and you did not ask for response handling :-)Zaller
Thanks again:) Have a nice day!Machicolate
L
1

Although this question has already had an accepted answer, however, I'd like to share my code that looks like your issue. Hope this helps!

I also use Interface like @Neo answer, as the following:

public interface VolleyResponseListener {
    void onError(String message);

    void onResponse(Object response);
}

Then in my VolleyUtils class:

public static void makeJsonObjectRequest(Context context, String url, final VolleyResponseListener listener) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (url, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    listener.onResponse(response);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    listener.onError(error.toString());
                }
            }) {

        @Override
        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
            try {
                String jsonString = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
                return Response.success(new JSONObject(jsonString),
                        HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JSONException je) {
                return Response.error(new ParseError(je));
            }
        }
    };

    // Access the RequestQueue through singleton class.
    VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
}

Then in Activity:

VolleyUtils.makeJsonObjectRequest(mContext, url, new VolleyResponseListener() {
        @Override
        public void onError(String message) {

        }

        @Override
        public void onResponse(Object response) {

        }
    });

P/S: my project uses Google's official Volley library, instead of using compile 'com.mcxiaoke.volley:library:1.0.17' in build.gradle. As a result, JsonObjectRequest(...) will have a difference at its definition.

Lindeberg answered 18/9, 2015 at 2:41 Comment(1)
Thanks for your response. I learned a lot from it and I will try this in my project. PS: I also use official Volley library:)Machicolate

© 2022 - 2024 — McMap. All rights reserved.