Android JSON Parsing Using Android Studio

Android JSON Parsing Using Android Studio.

In this article, we will be talking about JSON parsing in our android app using Android Studio. But before we dig in, we will talk about what JSON is and why we need it in our applications.

JSON:

JSON is an acronym for JAVASCRIPT OBJECT NOTATION and it is used for data exchange and storing. We use JSON because it is easy to access and much easier to read by humans. In JSON, we have key value pairs that mean data from JSON will have two parts; a variable/key and a value. Usually, JSON consists two types of nodes: objects and arrays.

Below is the example of JSON data.

1

 

The above JSON data is obtained by a URL, you can see the remaining JSON data on link below;

https://raw.githubusercontent.com/iCodersLab/JSON-Parsing-in-Android-using-Android-Studio/master/index.html

As shown above, curly brackets represent object and square brackets represent an array. In JSON, if your node starts with ‘{‘ you have to use getJSONObject() method and if your node starts with ‘[‘ you have to use getJSONArray() method.


TUTORIAL:

Let’s start parsing JSON. Before we begin, I’m assuming you have a properly working android studio.

1. Create a Project:

  • Go to files and create a new project with an empty activity and name it (I named it HomeScreen).

2

3


2. Grant Internet Access to your App:

  • As we are fetching our JSON data from a URL, we need to have internet access permission in our application.
  • For this, go to AndroidManifest.xml from android studio and add this permission.

<uses-permission android:name=”android.permission.INTERNET”/>

4


3. Edit your MainActivity.xml file:

  • Go to Android/res/layout/MainActivity.xml. (My file name is activity_home_screen.xml).
  • Add a relative layout and a list view, you can do this by drag and drop or by xml code.
  • Below is the xml code. (Your code should look similar to this).

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_home_screen"
android:background="@color/colorBackgroundMain"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="icoderslab.com.jsonparsing.HomeScreen">

<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>

 


4. Create ListView Row/Cell xml file:

  • Now you need to add listview row xml file where we will be showing our data.
  • Go to layout-> right click go to New-> add Layout Resource File-> name your xml file and click ok. (I named mine bucket_list.xml)
  • Add TextViews within LinearLayout(vertical), you can add as much TextViews as you want. But for now I’ll be adding text views for name, email, address, gender, mobile#, home#, office#.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<TextView
android:id="@+id/list_Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="casual"
android:textColor="@color/colorAccent"
android:textStyle="bold"
android:textSize="15dp" />
<TextView
android:id="@+id/list_Email"
android:fontFamily="casual"
android:textStyle="bold"
android:textColor="@color/colorPrimaryDark"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/list_Address"
android:fontFamily="casual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
<TextView
android:id="@+id/list_Gender"
android:fontFamily="casual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
<TextView
android:paddingTop="5dp"
android:id="@+id/list_Mobile"
android:fontFamily="casual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
<TextView
android:id="@+id/list_Home"
android:fontFamily="casual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
<TextView
android:id="@+id/list_Office"
android:fontFamily="casual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
</LinearLayout>

 


5. Add a java class to handle HTTP request:

  • Now we are going to do main coding for our application, we will add a class to our project (I have called it HTTP_Handler)
  • In this class we will be requesting information from the URL over HTTP request from the server.

package icoderslab.com.jsonparsing;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
/**
* Created by OsamaArshad on 07-Nov-16.
*/
public class HTTP_Handler {
private static final String classtag= HTTP_Handler.class.getSimpleName();  //return name of underlying class

public String makeHTTPCall(String URLinput) { // method which will request to server when provided with url
String response = null;
try {
URL url = new URL(URLinput);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //to open connection with url
conn.setRequestMethod("GET");   //request type is of GET, which means to get information from the server

InputStream in = new BufferedInputStream(conn.getInputStream()); //storing the input stream we are getting for the url
response = InputStreamToString(in); //now storing string from the input stream
} catch (MalformedURLException e) {
Log.e(classtag, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(classtag, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(classtag, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(classtag, "Exception: " + e.getMessage());
}
return response; //returning whatever we fetching from the string to the method.
}
private String InputStreamToString(InputStream is) {   //fetching string form the input stream
BufferedReader br = new BufferedReader(new InputStreamReader(is)); //it will read form stream
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = br.readLine()) != null) {
sb.append(line).append('\n'); //whatever we read from the stream, we will append it to the stringbuilder
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}


6. Add Code in MainActivity.java: (I’ve named it HomeScreen.java)

  1. Add all the necessary variables to your MainActivity (HomeScreen) class.
  2. Then add a class which will inherit from AsyncTask class, it will help us in managing all HTTP calling in a background thread.

What is AsyncTask?

AsyncTask is an abstract class which helps us perform long/background operations without affecting our UI thread. Which means if our app needs to wait for a response from the server in order to show us data, this class will help us do these processes without making our application non responsive (ANR).

Whenever a class inherits from AsyncTask class, it needs to override one method i.e. doInBackground() method.

In this application I will be using three methods from the AsyncTask synchronization criteria.

  1. onPreExecute(): In this method we will use a progress dialog before making an HTTP request.
  2. doInBackground(): In method, makeHTTPCall() method is used to fetch JSON from URL. When JSON is fetched, we will hash map key value pair technique to add data from JSON to the arraylist.
  3. onPostExecute(): In this method progress will be dismissed and all the data will be sent to the text views we’ve created before using list adapters.

Complete MainActivity.java code:


package icoderslab.com.jsonparsing;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class HomeScreen extends AppCompatActivity {
private String classtag= HomeScreen.class.getSimpleName();  //return name of underlying class
private ListView lv;
private ProgressDialog progress;
private String url="https://raw.githubusercontent.com/iCodersLab/JSON-Parsing-in-Android-using-Android-Studio/master/index.html"; //passing url
ArrayList<HashMap<String,String>> studentslist; //arraylist to save key value pair from json
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
studentslist=new ArrayList<>();
lv= (ListView) findViewById(R.id.list); //from home screen list view
new getStudents().execute(); // it will execute your AsyncTask
}
//--------------------------//-------------------------------//---------------------//
public class getStudents extends AsyncTask<Void,Void,Void> {
protected void onPreExecute(){
super.onPreExecute(); //it will use pre defined preExecute method in async task
progress=new ProgressDialog(HomeScreen.this);
progress.setMessage("Fetching JSON.,."); // show what you want in the progress dialog
progress.setCancelable(false); //progress dialog is not cancellable here
progress.show();
}
protected Void doInBackground(Void...arg0){
HTTP_Handler hh = new HTTP_Handler(); // object of HTTP_Handler
String jString = hh.makeHTTPCall(url); //calling makeHTTPCall method and string its response in a string
Log.e(classtag, "Response from URL: " + jString);
if (jString != null) {
try {
JSONObject jObj = new JSONObject(jString); //our json data starts with the object
JSONArray students = jObj.getJSONArray("studentsinfo"); //fetch array from studentsinfo object
for (int i = 0; i < students.length(); i++) {
JSONObject student = students.getJSONObject(i); //get object from i index
String id=student.getString("id");   //save string from variable 'id' to string
String name=student.getString("name");
String email=student.getString("email");
String address=student.getString("address");
String gender=student.getString("gender");

JSONObject phone=student.getJSONObject("phone"); //get object from phone
String mobile=phone.getString("mobile");  //save string from variable 'mobile' to string
String home=phone.getString("home");
String office=phone.getString("office");

HashMap<String, String> studentdata = new HashMap<>(); //create a hash map to set key and value pair

studentdata.put("id", id); //hash map will save key and its value
studentdata.put("name", name);
studentdata.put("email", email);
studentdata.put("address", address);
studentdata.put("gender",gender);
studentdata.put("mobile", mobile);
studentdata.put("home", home);
studentdata.put("office", office);
studentslist.add(studentdata); //now save all of the key value pairs to arraylist
}
} catch (final JSONException e) {
Log.e(classtag, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show(); //show if you catch any exception with data
}
});
}
} else {
Log.e(classtag, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check internet connection!",
Toast.LENGTH_LONG).show();//show if you are unable to connect with the internet or if jString is null
}
});
}
return null;
}
protected void onPostExecute(Void Result){
super.onPostExecute(Result);
if(progress.isShowing()){
progress.dismiss();
}
ListAdapter adapter=new SimpleAdapter(
HomeScreen.this,
studentslist,
R.layout.bucket_list,
new String[]{"name","email","address","gender","mobile","home","office"},
new int[]{R.id.list_Name,R.id.list_Email,R.id.list_Address ,R.id.list_Gender,R.id.list_Mobile,R.id.list_Home,R.id.list_Office});
lv.setAdapter(adapter);
//            SimpleAdapter (Context context,                   //
//                    List<? extends Map<String, ?>> data,      //
//            int resource,                                     //
//            String[] from,                                    //
//            int[] to)                                         //
//this will pass your json values to the bucket_list xml and whatever it is stored of key 'name' will be
// displayed to text view list_Name
}
}
}

Now run your application.


FINAL OUTPUT:

android-json-parsing-using-android-studio-output
android-json-parsing-using-android-studio-output

Download Code.

BY OSAMA ARSHAD.

One thought on “Android JSON Parsing Using Android Studio.

Leave a Reply

Your email address will not be published. Required fields are marked *