In previous post, I showed you how to use Volley to make a simple request in Android application.
This time, I’ll show you the recommended way to make a JSON request using Volley and how to customize Volley request to take advantage of the GSON library.
A - Setting up a RequestQueue
Firstly, create the VolleyHelper class. This will be a singleton class where we store and init all core Volley objects:
B - Make a JSON Request
Firstly, create the layout for our simple demo with one Button and one TextView to display the result:
In the MainActivity.java, we declare all indeed variables for all the controls and the JSON url:
Make sure that you remember to inject all the variables to the proper controls in the layout:
Then, the most important step is creating a JsonObjectRequest:
And add that JsonObjectRequest to RequestQueue in the Button click event:
Run the project and enjoy the result:
C - Custom the Request with GSON
In this section, I’ll describe how to implement a custom request types, for types that don’t have out-of-the-box Volley support - GSON Request.
As you know that GSON is a very famous and effective library used for JSON converting. Follow this link if you want to learn more about GSON.
If you want to implement a custom request, you have to do 2 steps:
- Extend the Request class, where represents the type of parsed response the request expects</p>
- Implement the abstract methods parseNetworkResponse() and deliverResponse()
Now apply all those steps to the GSONRequest class:The way to use GSONRequest is very familiar to normal requests. First, we need to create all the models class that equivalent to the JSON response: Product.javaProducts.javaIn MainActivity.java, we create a GSONRequest object:Then, add that GSONRequest object to the RequestQueue:Finally, run the project and enjoy the result: As you can see, I added one more button called GSON Request. That's all for this post, hope you enjoy this! :D