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
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.
implementation 'com.squareup.retrofit2:retrofit:2.5.0' implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
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.
<uses-permission android:name="android.permission.INTERNET"/>
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
import retrofit2.Call; import retrofit2.http.GET; public interface ApiInterface { String JSONURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/"; @GET("json_parsing.php") Call<String> getString(); }
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
public class RetroModel { private String name, country, city, id; public String getid() { return id; } public void setid(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
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
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000" android:text=" below information is fetched from URL With Retrofit"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv" android:layout_marginLeft="10dp" android:paddingTop="10dp" android:paddingBottom="10dp" android:textSize="20sp" android:textColor="#000" /> </LinearLayout>
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
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.scalars.ScalarsConverterFactory; public class MainActivity extends AppCompatActivity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.tv); getResponse(); } private void getResponse(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(ApiInterface.JSONURL) .addConverterFactory(ScalarsConverterFactory.create()) .build(); ApiInterface api = retrofit.create(ApiInterface.class); Call<String> call = api.getString(); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { Log.i("Responsestring", response.body().toString()); //Toast.makeText() if (response.isSuccessful()) { if (response.body() != null) { Log.i("onSuccess", response.body().toString()); String jsonresponse = response.body().toString(); writeTv(jsonresponse); } else { Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show(); } } } @Override public void onFailure(Call<String> call, Throwable t) { } }); } private void writeTv(String response){ try { //getting the whole json object from the response JSONObject obj = new JSONObject(response); if(obj.optString("status").equals("true")){ ArrayList<RetroModel> retroModelArrayList = new ArrayList<>(); JSONArray dataArray = obj.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { RetroModel retroModel = new RetroModel(); JSONObject dataobj = dataArray.getJSONObject(i); retroModel.setid(dataobj.getString("id")); retroModel.setName(dataobj.getString("name")); retroModel.setCountry(dataobj.getString("country")); retroModel.setCity(dataobj.getString("city")); retroModelArrayList.add(retroModel); } for (int j = 0; j < retroModelArrayList.size(); j++){ textView.setText(textView.getText()+ retroModelArrayList.get(j).getid()+ " "+ retroModelArrayList.get(j).getName() + " "+ retroModelArrayList.get(j).getCountry()+ " "+retroModelArrayList.get(j).getCity()+" \n"); } }else { Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }
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
private void getResponse(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(ApiInterface.JSONURL) .addConverterFactory(ScalarsConverterFactory.create()) .build(); ApiInterface api = retrofit.create(ApiInterface.class); Call<String> call = api.getString(); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { Log.i("Responsestring", response.body().toString()); //Toast.makeText() if (response.isSuccessful()) { if (response.body() != null) { Log.i("onSuccess", response.body().toString()); String jsonresponse = response.body().toString(); writeTv(jsonresponse); } else { Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show(); } } } @Override public void onFailure(Call<String> call, Throwable t) { } }); }
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.
String jsonresponse = response.body().toString();
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
private void writeTv(String response){ try { //getting the whole json object from the response JSONObject obj = new JSONObject(response); if(obj.optString("status").equals("true")){ ArrayList<RetroModel> retroModelArrayList = new ArrayList<>(); JSONArray dataArray = obj.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { RetroModel retroModel = new RetroModel(); JSONObject dataobj = dataArray.getJSONObject(i); retroModel.setid(dataobj.getString("id")); retroModel.setName(dataobj.getString("name")); retroModel.setCountry(dataobj.getString("country")); retroModel.setCity(dataobj.getString("city")); retroModelArrayList.add(retroModel); } for (int j = 0; j < retroModelArrayList.size(); j++){ textView.setText(textView.getText()+ retroModelArrayList.get(j).getid()+ " "+ retroModelArrayList.get(j).getName() + " "+ retroModelArrayList.get(j).getCountry()+ " "+retroModelArrayList.get(j).getCity()+" \n"); } }else { Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } }
For understanding above method, let us first check the JSON data which we have got.
{ "status": "true", "message": "Data fetched successfully!", "data": [ { "id": "1", "name": "Roger Federer", "country": "Switzerland", "city": "Basel" }, { "id": "2", "name": "Rafael Nadal", "country": "Spain", "city": "Madrid" }, { "id": "3", "name": "Novak Djokovic", "country": "Serbia", "city": "Monaco" }, { "id": "4", "name": "Andy Murray", "country": "United Kingdom", "city": "London" }, { "id": "5", "name": "Maria Sharapova", "country": "Russia", "city": "Moscow" }, { "id": "6", "name": "Caroline Wozniacki", "country": "Denmark", "city": "Odense" }, { "id": "7", "name": "Eugenie Bouchard", "country": "Canada", "city": " Montreal" }, { "id": "8", "name": "Ana Ivanovic", "country": "Serbia", "city": "Belgrade" } ] }
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
implementation 'com.android.volley:volley:1.1.1'
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
public class PlayerModel { private String name, country, city, id; public String getid() { return id; } public void setid(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
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
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" below infor is fetched from URL With volley"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tv" android:layout_marginLeft="10dp" android:paddingTop="10dp" android:paddingBottom="10dp" android:textSize="20sp" android:textColor="#000" android:text=""/> </LinearLayout>
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
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php"; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.tv); requestJSON(); } private void requestJSON(){ StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("strrrrr",">>"+response); try { //getting the whole json object from the response JSONObject obj = new JSONObject(response); if(obj.optString("status").equals("true")){ ArrayList<PlayerModel> playersModelArrayList = new ArrayList<>(); JSONArray dataArray = obj.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { PlayerModel playerModel = new PlayerModel(); JSONObject dataobj = dataArray.getJSONObject(i); playerModel.setid(dataobj.getString("id")); playerModel.setName(dataobj.getString("name")); playerModel.setCountry(dataobj.getString("country")); playerModel.setCity(dataobj.getString("city")); playersModelArrayList.add(playerModel); } for (int j = 0; j < playersModelArrayList.size(); j++){ textView.setText(textView.getText()+ playersModelArrayList.get(j).getid()+ " "+ playersModelArrayList.get(j).getName() + " "+ playersModelArrayList.get(j).getCountry()+ " "+playersModelArrayList.get(j).getCity()+" \n"); } }else { Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //displaying the error in toast if occurrs Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); //creating a request queue RequestQueue requestQueue = Volley.newRequestQueue(this); //adding the string request to request queue requestQueue.add(stringRequest); } }
Understandings Of Main Logic
Main logic and code is written in the Main Activity.
First of all, read the below lines
private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php"; private TextView textView;
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
private void requestJSON(){ StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("strrrrr",">>"+response); try { //getting the whole json object from the response JSONObject obj = new JSONObject(response); if(obj.optString("status").equals("true")){ ArrayList<PlayerModel> playersModelArrayList = new ArrayList<>(); JSONArray dataArray = obj.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { PlayerModel playerModel = new PlayerModel(); JSONObject dataobj = dataArray.getJSONObject(i); playerModel.setid(dataobj.getString("id")); playerModel.setName(dataobj.getString("name")); playerModel.setCountry(dataobj.getString("country")); playerModel.setCity(dataobj.getString("city")); playersModelArrayList.add(playerModel); } for (int j = 0; j < playersModelArrayList.size(); j++){ textView.setText(textView.getText()+ playersModelArrayList.get(j).getid()+ " "+ playersModelArrayList.get(j).getName() + " "+ playersModelArrayList.get(j).getCountry()+ " "+playersModelArrayList.get(j).getCity()+" \n"); } }else { Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //displaying the error in toast if occurrs Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); //creating a request queue RequestQueue requestQueue = Volley.newRequestQueue(this); //adding the string request to request queue requestQueue.add(stringRequest); }
Consider the below code
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring, new Response.Listener<String>() { @Override public void onResponse(String response) {
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.
try { //getting the whole json object from the response JSONObject obj = new JSONObject(response); if(obj.optString("status").equals("true")){ ArrayList<PlayerModel> playersModelArrayList = new ArrayList<>(); JSONArray dataArray = obj.getJSONArray("data");
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
{ "status": "true", "message": "Data fetched successfully!", "data": [ { "id": "1", "name": "Roger Federer", "country": "Switzerland", "city": "Basel" }, { "id": "2", "name": "Rafael Nadal", "country": "Spain", "city": "Madrid" }, { "id": "3", "name": "Novak Djokovic", "country": "Serbia", "city": "Monaco" }, { "id": "4", "name": "Andy Murray", "country": "United Kingdom", "city": "London" }, { "id": "5", "name": "Maria Sharapova", "country": "Russia", "city": "Moscow" }, { "id": "6", "name": "Caroline Wozniacki", "country": "Denmark", "city": "Odense" }, { "id": "7", "name": "Eugenie Bouchard", "country": "Canada", "city": " Montreal" }, { "id": "8", "name": "Ana Ivanovic", "country": "Serbia", "city": "Belgrade" } ] }
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
for (int i = 0; i < dataArray.length(); i++) { PlayerModel playerModel = new PlayerModel(); JSONObject dataobj = dataArray.getJSONObject(i); playerModel.setid(dataobj.getString("id")); playerModel.setName(dataobj.getString("name")); playerModel.setCountry(dataobj.getString("country")); playerModel.setCity(dataobj.getString("city")); playersModelArrayList.add(playerModel); }
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
for (int j = 0; j < playersModelArrayList.size(); j++){ textView.setText(textView.getText()+ playersModelArrayList.get(j).getid()+ " "+ playersModelArrayList.get(j).getName() + " "+ playersModelArrayList.get(j).getCountry()+ " "+playersModelArrayList.get(j).getCity()+" \n"); }
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
{ "status": "true", "message": "Data fetched successfully!", "data": [ { "id": "1", "name": "Roger Federer", "country": "Switzerland", "city": "Basel" }, { "id": "2", "name": "Rafael Nadal", "country": "Spain", "city": "Madrid" }, { "id": "3", "name": "Novak Djokovic", "country": "Serbia", "city": "Monaco" }, { "id": "4", "name": "Andy Murray", "country": "United Kingdom", "city": "London" }, { "id": "5", "name": "Maria Sharapova", "country": "Russia", "city": "Moscow" }, { "id": "6", "name": "Caroline Wozniacki", "country": "Denmark", "city": "Odense" }, { "id": "7", "name": "Eugenie Bouchard", "country": "Canada", "city": " Montreal" }, { "id": "8", "name": "Ana Ivanovic", "country": "Serbia", "city": "Belgrade" } ] }
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 <manifest>ā¦.</manifest> tag.
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Final code for AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.exampledemo.parsaniahardik.jsonparsing"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
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
public class AndyConstants { public class ServiceCode { public static final int HOME = 1; } // web service url constants public class ServiceType { public static final String URL = "http://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php"; } // webservice key constants public class Params { public static final String ID = "id"; public static final String NAME = "name"; public static final String COUNTRY = "country"; public static final String CITY = "city"; } }
Above class contain URL constants and Parameter constants.
Step 5: Creating AndyUtils
Create a Java class named AndyUtils and add below source code
import android.app.ProgressDialog; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class AndyUtils { private static ProgressDialog mProgressDialog; public static void showSimpleProgressDialog(Context context, String title, String msg, boolean isCancelable) { try { if (mProgressDialog == null) { mProgressDialog = ProgressDialog.show(context, title, msg); mProgressDialog.setCancelable(isCancelable); } if (!mProgressDialog.isShowing()) { mProgressDialog.show(); } } catch (IllegalArgumentException ie) { ie.printStackTrace(); } catch (RuntimeException re) { re.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static void showSimpleProgressDialog(Context context) { showSimpleProgressDialog(context, null, "Loading...", false); } public static void removeSimpleProgressDialog() { try { if (mProgressDialog != null) { if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); mProgressDialog = null; } } } catch (IllegalArgumentException ie) { ie.printStackTrace(); } catch (RuntimeException re) { re.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { return false; } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } }
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
import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; /** * Since HttpClient,BasicNameValuePairs, etc... are deprecated. * I've searched for a good alternative, and couldn't find any. Eventually ended up writing my own solution, so I decided to share to those who needs it. * Main goals: to make it intuitive, short, clean and reasonable. * NOTE methods: .prepare(), preparePost(), withData(map) & withData(string) are build to allow caller to chain in different variations, examples: *HttpRequest req=new HttpRequest("http://host:port/path"); * *Example 1: //prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29, return true - if worked *req.preparePost().withData("name=Bubu&age=29").send(); * *Example 2: //prepare http get request, send to "http://host:port/path" and read server's response as String *req.prepare().sendAndReadString(); * *Example 3: //prepare Http Post request and send to "http://host:port/path" with name=Bubu and age=29 and read server's response as JSONObject *HashMap<String, String>params=new HashMap<>(); params.put("name", "Groot"); params.put("age", "29"); *req.preparePost().withData(params).sendAndReadJSON(); */ public class HttpRequest { //Supported HttpRequest methods public static enum Method{ POST,PUT,DELETE,GET; } private URL url; private HttpURLConnection con; private OutputStream os; //After instantiation, when opening connection - IOException can occur public HttpRequest(URL url)throws IOException{ this.url=url; con = (HttpURLConnection)this.url.openConnection(); } //Can be instantiated with String representation of url, force caller to check for IOException which can be thrown public HttpRequest(String url)throws IOException{ this(new URL(url)); Log.d("parameters", url); } /** * Sending connection and opening an output stream to server by pre-defined instance variable url * * @param //isPost boolean - indicates whether this request should be sent in POST method * @throws IOException - should be checked by caller * */ private void prepareAll(Method method)throws IOException{ con.setDoInput(true); con.setRequestMethod(method.name()); if(method==Method.POST||method==Method.PUT){ con.setDoOutput(true); os = con.getOutputStream(); } } //prepare request in GET method //@return HttpRequest this instance -> for chaining method @see line 22 public HttpRequest prepare() throws IOException{ prepareAll(Method.GET); return this; } /** * Prepares HttpRequest method with for given method, possible values: HttpRequest.Method.POST, * HttpRequest.Method.PUT, HttpRequest.Method.GET & HttpRequest.Method.DELETE * * @param method HttpRequest.Method - nested enum HttpRequest.Method constant * @return HttpRequest this instance -> for chaining method @see line 22 * @throws IOException - should be checked by caller * */ public HttpRequest prepare(HttpRequest.Method method)throws IOException{ prepareAll(method); return this; } /** * Adding request headers (standard format "Key":"Value") * * @param headers String variadic params in standard format "Key":"Value" * @return HttpRequest this instance -> for chaining method @see line 22 * */ public HttpRequest withHeaders(String... headers){ for(int i=0,last=headers.length;i<last;i++) { String[]h=headers[i].split("[:]"); con.setRequestProperty(h[0],h[1]); } return this; } /** * Writes query to open stream to server * * @param query String params in format of key1=v1&key2=v2 to open stream to server * @return HttpRequest this instance -> for chaining method @see line 22 * @throws IOException - should be checked by caller * */ public HttpRequest withData(String query) throws IOException{ BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(query); writer.close(); return this; } /** * Builds query on format of key1=v1&key2=v2 from given hashMap structure * for map: {name=Bubu, age=29} -> builds "name=Bubu&age=29" * for map: {Iam=Groot} -> builds "Iam=Groot" * * @param params HashMap consists of key-> value pairs to build query from * @return HttpRequest this instance -> for chaining method @see line 22 * @throws IOException - should be checked by caller * */ public HttpRequest withData(HashMap<String,String> params) throws IOException{ StringBuilder result=new StringBuilder(); for(Map.Entry<String,String>entry : params.entrySet()){ result.append((result.length()>0?"&":"")+entry.getKey()+"="+entry.getValue());//appends: key=value (for first param) OR &key=value(second and more) Log.d("parameters",entry.getKey()+" ===> "+ entry.getValue()); } withData(result.toString()); return this; } //When caller only need to send, and don't need String response from server public int send() throws IOException{ return con.getResponseCode(); //return HTTP status code to indicate whether it successfully sent } /** * Sending request to the server and pass to caller String as it received in response from server * * @return String printed from server's response * @throws IOException - should be checked by caller * */ public String sendAndReadString() throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder response=new StringBuilder(); for(String line;(line=br.readLine())!=null;)response.append(line+"\n"); Log.d("ressss",response.toString()); return response.toString(); } /** * Sending request to the server and pass to caller its raw contents in bytes as it received from server. * * @return byte[] from server's response * @throws IOException - should be checked by caller * */ public byte[] sendAndReadBytes() throws IOException{ byte[] buffer = new byte[8192]; InputStream is = con.getInputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream(); for (int bytesRead;(bytesRead=is.read(buffer))>=0;)output.write(buffer, 0, bytesRead); return output.toByteArray(); } //JSONObject representation of String response from server public JSONObject sendAndReadJSON() throws JSONException, IOException{ return new JSONObject(sendAndReadString()); } }
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
import android.app.Activity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class ParseContent { private final String KEY_SUCCESS = "status"; private final String KEY_MSG = "message"; private Activity activity; ArrayList<HashMap<String, String>> arraylist; public ParseContent(Activity activity) { this.activity = activity; } public boolean isSuccess(String response) { try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.optString(KEY_SUCCESS).equals("true")) { return true; } else { return false; } } catch (JSONException e) { e.printStackTrace(); } return false; } public String getErrorCode(String response) { try { JSONObject jsonObject = new JSONObject(response); return jsonObject.getString(KEY_MSG); } catch (JSONException e) { e.printStackTrace(); } return "No data"; } public ArrayList<PlayersModel> getInfo(String response) { ArrayList<PlayersModel> playersModelArrayList = new ArrayList<>(); try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getString(KEY_SUCCESS).equals("true")) { arraylist = new ArrayList<HashMap<String, String>>(); JSONArray dataArray = jsonObject.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { PlayersModel playersModel = new PlayersModel(); JSONObject dataobj = dataArray.getJSONObject(i); playersModel.setName(dataobj.getString(AndyConstants.Params.NAME)); playersModel.setCountry(dataobj.getString(AndyConstants.Params.COUNTRY)); playersModel.setCity(dataobj.getString(AndyConstants.Params.CITY)); playersModelArrayList.add(playersModel); } } } catch (JSONException e) { e.printStackTrace(); } return playersModelArrayList; } }
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
public class PlayersModel { private String name, country, city; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
Step 9: Creating lv_item.xml layout file
Create a new layout resource file named lv_item.xml file and add following
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#000" android:orientation="vertical"> <TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:layout_marginTop="10dp" android:gravity="center_vertical" android:textAppearance="?android:attr/textAppearanceMedium" android:paddingLeft="10dp" android:text="Name" /> <TextView android:id="@+id/country" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:gravity="center_vertical" android:textAppearance="?android:attr/textAppearanceMedium" android:paddingLeft="10dp" android:text="Country" /> <TextView android:id="@+id/city" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:gravity="center_vertical" android:textAppearance="?android:attr/textAppearanceMedium" android:paddingLeft="10dp" android:text="City" /> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:background="@color/colorAccent"/> </LinearLayout>
Step 10: Create one class and name it: CustomeAdapter.java
Copy and paste following code in this class:
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; /** * Created by Parsania Hardik on 03-Jan-17. */ public class CustomeAdapter extends BaseAdapter { private Context context; private ArrayList<PlayersModel> playersModelArrayList; public CustomeAdapter(Context context, ArrayList<PlayersModel> playersModelArrayList) { this.context = context; this.playersModelArrayList = playersModelArrayList; } @Override public int getViewTypeCount() { return getCount(); } @Override public int getItemViewType(int position) { return position; } @Override public int getCount() { return playersModelArrayList.size(); } @Override public Object getItem(int position) { return playersModelArrayList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.lv_item, null, true); holder.tvname = (TextView) convertView.findViewById(R.id.name); holder.tvcountry = (TextView) convertView.findViewById(R.id.country); holder.tvcity = (TextView) convertView.findViewById(R.id.city); convertView.setTag(holder); }else { // the getTag returns the viewHolder object set as a tag to the view holder = (ViewHolder)convertView.getTag(); } holder.tvname.setText("Name: "+playersModelArrayList.get(position).getName()); holder.tvcountry.setText("Country: "+playersModelArrayList.get(position).getCountry()); holder.tvcity.setText("City: "+playersModelArrayList.get(position).getCity()); return convertView; } private class ViewHolder { protected TextView tvname, tvcountry, tvcity; } }
Step 11: Copy and Paste following code in activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorAccent" android:orientation="vertical" tools:context="com.exampledemo.parsaniahardik.jsonparsing.MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:layout_marginTop="10dp" android:textSize="20sp" android:textColor="#000" android:text="Data from JSON Parsing"/> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/lv"/> </LinearLayout>
Step 12: Copy following code in MainActivity.java
import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ListView; import android.widget.Toast; import org.json.JSONException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private ParseContent parseContent; private final int jsoncode = 1; private ListView listView; private ArrayList<PlayersModel> playersModelArrayList; private CustomeAdapter customeAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); parseContent = new ParseContent(this); listView = (ListView) findViewById(R.id.lv); try { parseJson(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } private void parseJson() throws IOException, JSONException { if (!AndyUtils.isNetworkAvailable(MainActivity.this)) { Toast.makeText(MainActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show(); return; } AndyUtils.showSimpleProgressDialog(MainActivity.this); new AsyncTask<Void, Void, String>(){ protected String doInBackground(Void[] params) { String response=""; HashMap<String, String> map=new HashMap<>(); try { HttpRequest req = new HttpRequest(AndyConstants.ServiceType.URL); response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString(); } catch (Exception e) { response=e.getMessage(); } return response; } protected void onPostExecute(String result) { //do something with response Log.d("newwwss",result); onTaskCompleted(result,jsoncode); } }.execute(); } public void onTaskCompleted(String response, int serviceCode) { Log.d("responsejson", response.toString()); switch (serviceCode) { case jsoncode: if (parseContent.isSuccess(response)) { AndyUtils.removeSimpleProgressDialog(); //will remove progress dialog playersModelArrayList = parseContent.getInfo(response); customeAdapter = new CustomeAdapter(this,playersModelArrayList); listView.setAdapter(customeAdapter); }else { Toast.makeText(MainActivity.this, parseContent.getErrorCode(response), Toast.LENGTH_SHORT).show(); } } } }
Step 13: Description of MainActivity.java
Look at below source code
private void parseJson() throws IOException, JSONException { if (!AndyUtils.isNetworkAvailable(MainActivity.this)) { Toast.makeText(MainActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show(); return; } AndyUtils.showSimpleProgressDialog(MainActivity.this); new AsyncTask<Void, Void, String>(){ protected String doInBackground(Void[] params) { String response=""; HashMap<String, String> map=new HashMap<>(); try { HttpRequest req = new HttpRequest(AndyConstants.ServiceType.URL); response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString(); } catch (Exception e) { response=e.getMessage(); } return response; } protected void onPostExecute(String result) { //do something with response Log.d("newwwss",result); onTaskCompleted(result,jsoncode); } }.execute(); }
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.
HttpRequest req = new HttpRequest(AndyConstants.ServiceType.URL); response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
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).
protected void onPostExecute(String result) { //do something with response Log.d("newwwss",result); onTaskCompleted(result,jsoncode); }
From above method, JSON Data is sent to the onTaskCompleted() method.
public void onTaskCompleted(String response, int serviceCode) { Log.d("responsejson", response.toString()); switch (serviceCode) { case jsoncode: if (parseContent.isSuccess(response)) { AndyUtils.removeSimpleProgressDialog(); //will remove progress dialog playersModelArrayList = parseContent.getInfo(response); customeAdapter = new CustomeAdapter(this,playersModelArrayList); listView.setAdapter(customeAdapter); }else { Toast.makeText(MainActivity.this, parseContent.getErrorCode(response), Toast.LENGTH_SHORT).show(); } } }
JSON Parsing in android is done by getInfo() method of ParseContent class. Following is getInfo() method.
public ArrayList<PlayersModel> getInfo(String response) { ArrayList<PlayersModel> playersModelArrayList = new ArrayList<>(); try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getString(KEY_SUCCESS).equals("true")) { arraylist = new ArrayList<HashMap<String, String>>(); JSONArray dataArray = jsonObject.getJSONArray("data"); for (int i = 0; i < dataArray.length(); i++) { PlayersModel playersModel = new PlayersModel(); JSONObject dataobj = dataArray.getJSONObject(i); playersModel.setName(dataobj.getString(AndyConstants.Params.NAME)); playersModel.setCountry(dataobj.getString(AndyConstants.Params.COUNTRY)); playersModel.setCity(dataobj.getString(AndyConstants.Params.CITY)); playersModelArrayList.add(playersModel); } } } catch (JSONException e) { e.printStackTrace(); } return playersModelArrayList; }
Our JSON data starting from ‘{‘ bracket so it is JSONObject. So the starting ‘{‘ is parse by below line
JSONObject jsonObject = new JSONObject(response);
After that, we have key named “data” and its value is starting from ‘[‘ bracket which is JSONArray. It is parse by following line.
JSONArray dataArray = jsonObject.getJSONArray("data");
Now data array contains 8 objects so they are parsed by for loop and it is stored in instance of PlayersModel Class.
for (int i = 0; i < dataArray.length(); i++) { PlayersModel playersModel = new PlayersModel(); JSONObject dataobj = dataArray.getJSONObject(i); playersModel.setName(dataobj.getString(AndyConstants.Params.NAME)); playersModel.setCountry(dataobj.getString(AndyConstants.Params.COUNTRY)); playersModel.setCity(dataobj.getString(AndyConstants.Params.CITY)); playersModelArrayList.add(playersModel); }
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 š