Wednesday, May 22, 2013

Example using Volley Google Framework (very simple)

First you can download the Git where I did create a small lib project that have OkHttp and Volley together, to use it as library project or export the .jar file to use it on your projects.

If you want to use the project where I did put both together to facilitate the life (at least for myself), you need, after you have opened the project in the Eclipse, right click on the project name –> Properties –> Android , then scroll down to the bottom and check the box where says isLibrary , then Apply and Ok.

image

After you have done that you can open your project, and going over your project name doing right click –> Properties –> Android, then scroll down to the bottom and click on add and select your library project that in this case is called GoogleHttpFramework, click Ok, then Apply and Ok.

image

Doing this you will have create the link just like you would do inserting the jar in your built path.

Now if you want to export the .jar file, it’s quite simple, it’s just right click over the project, in this case the GoogleHttpFramework then Export –> Java –> JAR File, uncheck all checkboxes like the image bellow, select the project and the path that you want have the .jar generated, then click finish.

image

Then you can copy the .jar to you /lib folder inside your project.

image

From now on you have access to your jar or of your library project.

Then you can open my very simple example that you have downloaded from the Git also. The example project is called RestFulClient.

This example is quite simple and you have only two buttons in the screen one will call a rest service that send us a bad formatted JSON object and consequently will generate an error, that will display it to you in a TextView on your screen, the second button will make a simple call to a Yahoo rest ws and will return a number that should be translated to a Date, however the number doesn’t seem come in a real long number, meaning that the date will basically be the same just having differences on the seconds.

I’m using two URLs that I got from the web, for don’t have to create a server side project that would take some time, as this is a quite simple example and we just need one working well and other failing.

Here is the method where the Volley makes the call to the Rest WS.

private void getService(String url) {
//        JSONObject reqBody = new JSONObject();
        Map<String,String> params = new HashMap<String,String>();
        if (url.equals(URL_SUCCESS)) {
            try {
                params.put("appid", "YahooDemo");
                params.put("output", "json");
                url = addParamsToUrl(url, params);
//                reqBody.put("appid", "YahooDemo");
//                reqBody.put("output", "json");
                volleyRequestQueue = Volley.newRequestQueue(this);
                // GET
                volleyRequestQueue.add(new JsonObjectRequest(Method.GET, url, null, new MyResponseListener(), new MyErrorListener()));
                
                // POST 
                // Need to comment at least the line 86 where url receive the par1ameters and uncomment lines 79, 87 and 88
                // However this url doesn't seems accept post, you need to try a different URL or create your own for test purpose
//                volleyRequestQueue.add(new JsonObjectRequest(Method.POST, url, reqBody, new MyResponseListener(), new MyErrorListener()));
            } catch (Exception e) {
                Log.e("ErrorListener", e.getLocalizedMessage());
            }
        } else {
            params.put("level", "1");
            url = addParamsToUrl(url, params);
            volleyRequestQueue = Volley.newRequestQueue(this);
            volleyRequestQueue.add(new JsonObjectRequest(Method.GET, url, null, new MyResponseListener(), new MyErrorListener()));
        }
    }







and here the piece of code for the class response.


class MyResponseListener implements Listener<JSONObject> {
 
        @Override
        public void onResponse(JSONObject response) {
            MainActivity.this.jsonObj = response;
            try {
                JSONObject result = MainActivity.this.jsonObj.getJSONObject("Result");
                String timestamp = result.getString("Timestamp");
                MainActivity.this.resultTxt.setText(new Date(Long.parseLong(timestamp.trim())).toString());
            } catch (Exception e) {
                Log.e("ErrorListener", e.getLocalizedMessage());
            }
        }
    }



 


and the class error.


class MyErrorListener implements ErrorListener {
 
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("ErrorListener", error.getCause() + "");
            if (error.getCause() != null) {
                Log.e("ErrorListener", error.getLocalizedMessage());
            }
            MainActivity.this.resultTxt.setText(error.toString());
            volleyRequestQueue.cancelAll(this);
        }
    }




I didn’t have tested thoroughly the Volley framework yet and as I’m progressing will posting more examples, I hope that this small example will help you when using HTTP requests and response. As Volley is a very powerful tool where you can create multi-thread requests and responses and also it’s deal with all try/catch’s and many other features that make HTTP easier to use, and it’s also compatible from Android 2.2 (API 8) to the latest.


Here the link on You Tube to watch the speech at Google I/O 2013 from the Volley with Ficus Kirkpatrick.


If you have any doubt or something do add please feel free to send me a email or post a comment.