简体   繁体   中英

Android Volley: Static vs Object

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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM