- Android JSON Parsing From Url With Volley, Retrofit And httpurlconnection
- 1. Android JSON Parsing From URL Using Retrofit
- Check Final Texts
- Basics about Retrofit
- Step 1. Write Retrofit Dependency
- Give Internet Permission
- Step 2. Making Interface
- Step 3. Making the Model class
- Step 4. Final Modifications
- Reading above source code
- 2. Android JSON Parsing Using Volley
- Final Looks of JSON Volley
- Information About Volley
- Steps To Make Example
- Step 1. Dependency part
- Step 2. Model For Players
- Step 3. Main Files
- Understandings Of Main Logic
- 3. Android httpurlconnection post JSON example
- JSON Data Which We Will Parse In JSON Parsing Android Tutorial
- How to Parse JSON Data
- Step 2: Updating AndroidManifest.xml file
- Step 3: Adding common classes
- Names of the classes are:
- Step 4: Creating AndyConstants
- Step 5: Creating AndyUtils
- Step 6: Preparing HttpRequest Class
- Step 7: Creating ParseContent
- Step 8: Creating Model Class
- Step 9: Creating lv_item.xml layout file
- Step 10: Create one class and name it: CustomeAdapter.java
- Step 11: Copy and Paste following code in activity_main.xml
- Step 12: Copy following code in MainActivity.java
- Step 13: Description of MainActivity.java
Android JSON Parsing From Url With Volley, Retrofit And httpurlconnection
Learn today about android json parsing from URL using Retrofit,Volley and HTTP.
We will create three examples as per the below.
1. Android JSON Parsing From URL Using Retrofit
We will learn how to parse JSON from URL or Server Using Retrofit Library in android.
You will learn how to fetch/retrieve data from MySQL database in android using JSON, retrofit, and PHP.
When you want to interact with a remote server such as to get data from a server or to send data to a remote servers, you need to make HTTP calls.
Retro fit is the library which make this task easier and faster.
Check Final Texts
Below video demonstrate how the outcome of this project will look a like
Basics about Retrofit
Square have developed the retrofit library.
Retrofit is the REST client for Java and Android development.
This library makes development tasks easier to get or send the data in the JSON format.
Retrofit uses the OkHttp library for HTTP requests. It also handles the cache operations itself with any coding from app developer.
Generally, developers make custom classes to parse JsonArray or JsonObject separately.
In this tutorial, we will get the JSON response in the string format. Then we can use android’s built in classes like JSONArray and JSONObject to parse the JSON in string format.
So now follow all the below steps of this example.
Step 1. Write Retrofit Dependency
First of all, make a new project in android studio.
Write down the following two lines in the build.gradle(Module:app) file.
First line will integrate the required classes for retrofit.
Second one will get the files for scalar library.
Retrofit will help us to make http calls to the remote web server. While scalar will convert the JSON response in the string format for us.
Give Internet Permission
Add the below line in the AndroidManifest.xml file.
This line will allow our project to use the internet of the android device.
Step 2. Making Interface
For making the http call, we need to create one interface.
Make a new JAVA class and give it a name ApiInterface.java
Below is the source code for ApiInterface.java
First string variable holds the path of the URL. This variable do not include the name of the file.
I have set the file name in the @GET annotation.
Then we need to define the call function. Name of the function is getString().
Step 3. Making the Model class
Model class will help us to maintain the proper data structure.
Make a new class named RetroModel.java and copy the below source code in it
Our JSON response holds the information like name, country, city, id.
So the above class includes the getter and setter methods for all these parameters.
We will use these methods to send and receive data in the MainActivity.java file.
Step 4. Final Modifications
When you created the new project in android studio, you should have two file in the project. activity_main.xml and MainActivity.java
Write the below code structure in activity_main.xml file
I have written two textviews in the above file.
First textview is static and it is just saying that below information is fetched using retrofit.
Second textview will hold the JSON data. We will insert the data in this textview in Main Activity.
Code snippet for MainActivity.java file looks like the below
Reading above source code
In the onCreate() method, compiler will first get the id of the text view.
Then it will call the method getResponse().
getResponse() method looks like the following
First of all, compiler will make the object of the Retrofit class.
Here, it will bind the URL using .baseUrl() method.
Then it will create the object of the interface ApiInterface. Using this object, it will create new Callback and will run the .enqueue() method.
After this much, retrofit have make the http call to the URL and it has get the response.
Compiler will read the JSON response in the onResponse() method.
Below line will give us the JSON response in the String format.
Then compiler will call the writeTv(jsonresponse) method. Compiler will pass the string variable which holds the JSON response in the parameter of this method.
Code structure for writeTv(jsonresponse) method is as the below
For understanding above method, let us first check the JSON data which we have got.
First of all, compiler will parse the parent object from the JSON response.
Then from this parent object, it will check the value of the “status” field.
If it is true, then it will create one arraylist with objects of the RetroModel class, which we have written in the Step 3.
Now compiler will create one JSONArray which is represented by the field “data“.
After this, it will make one for loop. During every iteration of this for loop, compiler will create the object of the RetroModel class and it will set the data with this object.
Then it will add this object into the arraylist.
Now another for loop is there. In this for loop, compiler will set the data in to the text view.
2. Android JSON Parsing Using Volley
Welcome to Android JSON Parsing Using Volley From URL Example Tutorial.
We will learn how to parse JSON from URL or Server Using Volley Library.
You will learn how to fetch/retrieve data from MySQL database in android using json, volley and PHP.
When we want to interact with the remote server, we need to send and fetch data over internet.
For example, when making registration and login module, we need to send username and password to remote server when user completes sign up task.
When user wants to login again, we need to fetch those username and password from the remote server.
In this process of sending and fetching data, we have to make some bridge between android device and remote server.
This tutorial uses Volley as a bridge.
Volley will return our json text in the string format.
Final Looks of JSON Volley
Information About Volley
Volley is a networking library developed by google.
It is an HTTP library that makes networking for android apps easier and faster.
We can also use AsyncTask class for networking purpose which is in-built class for android system.
Main drawback of using AsynTask is it’s inaccuracy. Also little time consuming problem is there for this class.
Steps To Make Example
Follow all the below steps to make a sample project in android studio.
We will fetch JSON data using volley and parse this data using JSONArray and JSONObject class.
Step 1. Dependency part
All the classes of the Volley library are not included in the core android structure.
They are available on GitHub but not in local android library.
So we need to fetch the volley classes in our project using dependency concept.
Add the below line in build.gradle(Module:app) file
Above line will enable us to use volley library in our project.
Step 2. Model For Players
Now let us create a model class. This class mainly includes getter and setter methods for the various data types.
For example, we have id, name, county and city of the players.
So we will have separate getter and setter methods for all four data types.
Make a new JAVA class named PlayerModel.java
Copy the below code in PlayerModel.java
As you can see that we have required methods for all four data types in above class.
We will use getter methods to fetch the data from the JSON response.
Setter methods will help us to set the data in appropriate UI widget.
Step 3. Main Files
Ok, now last thing is to change activity_main.xml and MainActivity.java files.
Write down below code structure in activity_main.xml
I have defined two textviews in this file.
First one is just saying that compiler have fetched the below data from URL.
Second one will hold all the data from json response.
Now add the following coding lines into MainActivity.java file
Understandings Of Main Logic
Main logic and code is written in the Main Activity.
First of all, read the below lines
First line is declaring one string variable named “URLstring” . This string includes the URL from which we will fetch JSON response.
Second one is making an object of the textview where we will set the data.
requestJSON() method
in onCreate() method, I have written a requestJSON() method, which will parse the json.
Following is the coding layout for requestJSON() method
Consider the below code
Compiler will create an object of the StringRequest class.
First parameter will decide whether volley will execute GET request or POST request. Our URL do not need any URL parameter so we will execute GET request.
Second parameter includes the string variable. This string variable represents the URL which will give us JSON response.
When the volley get any response from the URL, compiler will run onResponse() method.
We will receive our response via the parameter of onResponse() method.
Look at the below few starting lines of onResponse() method.
Compiler will implement try statement so that if any execution is there, we can avoid force close (app crashing) of our app.
JSON response is looking like below
Under try statement, compiler will first get the JSON Object.
then it will check the status.
If the status is true, then it will create an Arraylist with the objects of the PlayerModel class.
Then it will create a JSONArray named “data”. You can see the JSON array named “data” in above JSON response.
Now consider following code snippet
Compiler will execute one for loop.
Here, it will create an object of PlayerModel class and an object of JSONObject class.
The it will get the id, name, country and city of the players and will set them using setter methods.
After this, compiler will add the object to the arraylist.
After populating the arraylist with the data of the JSON response, compiler will execute below loop
We will write text in the textview using the above loop. It will write all the information about each player during every iteration of the loop.
3. Android httpurlconnection post JSON example
Hello, developers. Welcome to JSON Parsing Android Studio Example.
In JSON Parsing Android Studio simple example you will learn how to parse simple JSON data from URL step by step.
We will programmatically parse JSON with JSONObject and JSONArray classes in JSON Parsing In Android.
You will get the professional format to call remote Web Services in proper and easiest way at the end of JSON Parsing Android example.
You may find this JSON Parsing Android tutorial little lengthy but once you give it 10 minutes, you will be able to call all web services easily in all your future apps.
First, check the output of JSON Parsing Android tutorial and then we will create it.
JSON Data Which We Will Parse In JSON Parsing Android Tutorial
How to Parse JSON Data
JSON Parsing Android is not a very big thing.
Mainly there are only two main things in JSON data. First is JSON Object which is indicated by curly brackets .
Second is JSON Array which is indicated by square brackets [ ].
JSONObject class (Inbuilt Java Class) is used to parse JSONObject and JSONArray (Inbuilt Java Class) class is used to parse JSONArray.
We will see how to parse these two with special method later in the JSON Parsing Android tutorial. Now go to Android Studio.
Step 2: Updating AndroidManifest.xml file
add required permissions between …. tag.
Final code for AndroidManifest.xml file
Step 3: Adding common classes
We will add some common classes which contain constant variables and public methods.
We can use these variables and methods anywhere in the whole project so that it will reduce data redundancy.
Means that we will write them only once and then we can use them anytime and anywhere when needed.
Names of the classes are:
- AndyConstants
- AndyUtils
- HttpRequest
- ParseContent
Step 4: Creating AndyConstants
Create a new Java class and copy following source code
Above class contain URL constants and Parameter constants.
Step 5: Creating AndyUtils
Create a Java class named AndyUtils and add below source code
This class contains a methods to show(showSimplrProgressDialog()) and remove(removeSimpleProgressDialog()) progress dialog when app is fetching JSON data from server.
AndyUtils also includes a method (isNetworkAvailable()) to check whether the Internet of Android device is on or off.
Step 6: Preparing HttpRequest Class
Make new Java class named HttpRequest and paste following source code
We will use methods of this class to establish a connection between an Android device and web server.
Step 7: Creating ParseContent
Open new Java class and give it a name ParseContent, then Add below source code
In above source code, isSuccess(String response) method is used to check whether a status of response is true or false (see in JSON data above).
getErrorCode(String response) method is used to get the message of JSON data (see in JSON data above).
getInfo(String response) method will parse JSON data. I will describe this method later.
Step 8: Creating Model Class
We will display JSON Data in ListView, so create a new class named “PlayersModel” and add following
Step 9: Creating lv_item.xml layout file
Create a new layout resource file named lv_item.xml file and add following
Step 10: Create one class and name it: CustomeAdapter.java
Copy and paste following code in this class:
Step 11: Copy and Paste following code in activity_main.xml
Step 12: Copy following code in MainActivity.java
Step 13: Description of MainActivity.java
Look at below source code
First, we will check the internet of the device. If it is off, then give message that “Internet is required!”
If internet is on then we will call a web service to get JSON.
Following will call web service.
We will get JSON Data in String Format into variable named “response.”
These JSON Data is sent to onPostExecute(String result) method. Below is code of onPostExecute(String result).
From above method, JSON Data is sent to the onTaskCompleted() method.
JSON Parsing in android is done by getInfo() method of ParseContent class. Following is getInfo() method.
After that, we have key named “data” and its value is starting from ‘[‘ bracket which is JSONArray. It is parse by following line.
Now data array contains 8 objects so they are parsed by for loop and it is stored in instance of PlayersModel Class.
After getting playersModelArrayList from getInfo() method, listview is populated using custom adapter.
So that’s all for JSON Parsing Android Studio example, Feel free to comment on your queries and reviews. Thank you 🙂
Источник