Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Android JSON Parsing Tutorial

4.85/5 (4 votes)
17 Jul 2016CPOL6 min read 35.4K  
Android JSON parsing tutorial

JSON(JavaScript Object Notation), is a language independent data format that uses human-readable text to transmit data objects consisting of key-value pairs.

In this tutorial, we will explain the structure of JSON response and how to parse the response in order to get the required information. To explain the concept, we would be using two sample JSON responses:

[{"rom":"32GB","screenSize":"5.5 inch","backCamera":"21MP","companyName":"Motorola","name":"Moto X Play","frontCamera":"5MP","battery":"3630mAH","operatingSystem":"Android 5.1","processor":"1.8GHz","url":"http://www.androidtutorialpoint.com/api/motorola_moto_x_play","ram":"2GB"},{"rom":"8GB","screenSize":"4 inch","backCamera":"5MP","companyName":"Samsung","name":"Galaxy S Duos 3","frontCamera":"0.3MP","battery":"1500mAH","operatingSystem":"Android 4.4","processor":"1.2GHz","url":"http://www.androidtutorialpoint.com/api/samsung_galaxy_s_dous_3","ram":"512MB"},{"rom":"64GB","screenSize":"4.7 inch","backCamera":"12MP","companyName":"Apple","name":"Iphone 6S","frontCamera":"5MP","battery":"1715mAH","operatingSystem":"iOS 9","processor":"1.84GHz","url":"http://www.androidtutorialpoint.com/api/apple_iphone_6s","ram":"2GB"},{"rom":"16GB","screenSize":"5.2 inch","backCamera":"12.3MP","companyName":"LG","name":"Nexus 5X","frontCamera":"5MP","battery":"1500mAH","operatingSystem":"Android 6","processor":"1.8GHz","url":"http://www.androidtutorialpoint.com/api/lg_nexus_5x","ram":"2GB"}]
{"rom":"32GB","screenSize":"5.5 inch","backCamera":"21MP","companyName":"Motorola","name":"Moto X Play","frontCamera":"5MP","battery":"3630mAH","operatingSystem":"Android 5.1","processor":"1.8GHz","url":"http://www.androidtutorialpoint.com/api/motorola_moto_x_play","ram":"2GB"}

These links consist of sample JSON Responses for JSON Array and JSON Object respectively. Before starting to build app, let’s dig a bit into the structure of a JSON response.

Java
Consider following JSON Response :

[
        {
            "rom":"32GB",
            "screenSize":"5.5 inch",
            "backCamera":"21MP",
            "companyName":"Motorola",
            "name":"Moto X Play",
            "frontCamera":"5MP",
            "battery":"3630mAH",
            "operatingSystem":"Android 5.1",
            "processor":"1.8GHz",
            "url":"http://www.androidtutorialpoint.com/api/motorola_moto_x_play",
            "ram":"2GB"
        },
        {
            "rom":"8GB",
            "screenSize":"4 inch",
            "backCamera":"5MP",
            "companyName":"Samsung",
            "name":"Galaxy S Duos 3",
            "frontCamera":"0.3MP",
            "battery":"1500mAH",
            "operatingSystem":"Android 4.4",
            "processor":"1.2GHz",
            "url":"http://www.androidtutorialpoint.com/api/samsung_galaxy_s_dous_3",
            "ram":"512MB"},{"rom":"64GB",
            "screenSize":"4.7 inch",
            "backCamera":"12MP",
            "companyName":"Apple",
            "name":"Iphone 6S",
            "frontCamera":"5MP",
            "battery":"1715mAH",
            "operatingSystem":"iOS 9",
            "processor":"1.84GHz",
            "url":"http://www.androidtutorialpoint.com/api/apple_iphone_6s",
            "ram":"2GB"
        },
        {
            "rom":"16GB",
            "screenSize":"5.2 inch",
            "backCamera":"12.3MP",
            "companyName":"LG",
            "name":"Nexus 5X",
            "frontCamera":"5MP",
            "battery":"1500mAH",
            "operatingSystem":"Android 6",
            "processor":"1.8GHz",
            "url":"http://www.androidtutorialpoint.com/api/lg_nexus_5x",
            "ram":"2GB"
        }
            ]

As apparent from the above, a JSON Response can have the following elements:

  1. JSON Array([): In a JSON file, square bracket ([) represents a JSON array.
  2. JSON Objects({): In a JSON file, curly bracket ({) represents a JSON object.
  3. Key: A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object.
  4. Value: Each key has a value that could be string , integer or double, etc.

Android provides the following classes to manipulate a JSON response:
JSONObjectJSONArray, JSONStringer and JSONTokener. We will be talking about org.json.JSONObject and org.json.JSONArray in this tutorial.

To parse a JSON response, first identify the fields in the JSON response that you are interested in. For example, in the JSON given above in the link, we will be using all the fields. We have to write our parse function accordingly.

Let’s go step by step to make a sample JSON parsing app. We will demonstrate how to parse a JSON Object and a JSON Array. In this app, we will retrieve the details of Mobile Phones from the JSON String provided at a given URL and then display them as a list, on clicking each individual Mobile, details of the mobile will be displayed.

Pre-requisites

  1. Android Studio installed on your PC (Unix or Windows).
  2. A real time Android device (Smartphone or Tablet) configured with Android Studio.

Creating a New Project

  1. Open Android Studio and create a new project “JSONParser” and company domain application.example.com (We have used our company domain, i.e., androidtutorialpoint.com. Similarly you can use yours).
  2. Click Next and choose Min SDK, we have kept the default value. Again, click Next and choose Blank Activity .
  3. Name the Activity JSONParseActivity and click next.
  4. Leave all other things as default and Click Finish.

A new project will be created and gradle will resolve all the dependencies.
Next create a mobile class. Mobile class represents the model of a mobile, i.e., it contains all the fields and methods (getter and setter) required by a Mobile. So create a new Java class Mobile.java and put the following code in it.

Mobile.java

Java
package com.androidtutorialpoint.jsonparser;
import java.io.Serializable;

public class Mobile implements Serializable{
    private String mName;
    private String mCompanyName;
    private String mOperatingSystem;
    private String mProcessor;
    private String mRam;
    private String mRom;
    private String mFrontCamera;
    private String mBackCamera;
    private String mScreenSize;
    private String mBattery;
    private String mUrl;
    public String getName() {
        return mName;
    }
    public void setName(String mName) {
        this.mName = mName;
    }
    public String getCompanyName() {
        return mCompanyName;
    }
    public void setCompanyName(String mCompanyName) {
        this.mCompanyName = mCompanyName;
    }
    public String getOperatingSystem() {
        return mOperatingSystem;
    }
    public void setOperatingSystem(String mOperatingSystem) {
        this.mOperatingSystem = mOperatingSystem;
    }
    public String getProcessor() {
        return mProcessor;
    }
    public void setProcessor(String mProcessor) {
        this.mProcessor = mProcessor;
    }
    public String getRam() {
        return mRam;
    }
    public void setRam(String mRam) {
        this.mRam = mRam;
    }
    public String getRom() {
        return mRom;
    }
    public void setRom(String mRom) {
        this.mRom = mRom;
    }
    public String getFrontCamera() {
        return mFrontCamera;
    }
    public void setFrontCamera(String mFrontCamera) {
        this.mFrontCamera = mFrontCamera;
    }
    public String getBackCamera() {
        return mBackCamera;
    }
    public void setBackCamera(String mBackCamera) {
        this.mBackCamera = mBackCamera;
    }
    public String getScreenSize() {
        return mScreenSize;
    }
    public void setScreenSize(String mScreenSize) {
        this.mScreenSize = mScreenSize;
    }
    public String getBattery() {
        return mBattery;
    }
    public void setBattery(String mBattery) {
        this.mBattery = mBattery;
    }
    public String getUrl() {
        return mUrl;
    }
    public void setUrl(String mUrl) {
        this.mUrl = mUrl;
    }
}

We are implementing Serializable interface as we will be passing Mobile object from one activity to other.
Next, create two functions parseFeed() and parseArrayFeed() to parse the JSONObject and JSONArray respectively. While parsing the JSON response, we might get an org.json.JSONException so we will write the parsing logic in a try/catch block.
parseFeed() takes JSONObject as a parameter and sets all the attributes of the mobile object.

JSONParser.java

Java
package com.androidtutorialpoint.jsonparser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;

public class JSONParser {
   public static ArrayList<Mobile> mMobiles = new ArrayList<>();
    public static Mobile parseFeed(JSONObject obj) {

        try {
                Mobile mobile = new Mobile();
                mobile.setName(obj.getString("name"));
                mobile.setCompanyName(obj.getString("companyName"));
                mobile.setOperatingSystem(obj.getString("operatingSystem"));
                mobile.setProcessor(obj.getString("processor"));
                mobile.setBackCamera(obj.getString("backCamera"));
                mobile.setFrontCamera(obj.getString("frontCamera"));
                mobile.setRam(obj.getString("ram"));
                mobile.setRom(obj.getString("rom"));
                mobile.setScreenSize(obj.getString("screenSize"));
                mobile.setUrl(obj.getString("url"));
                mobile.setBattery(obj.getString("battery"));
                return mobile;
            } catch (JSONException e1) {
            e1.printStackTrace();
            return null;
        }
    }

parseArrayFeed() takes JSONArray as a parameter and returns an ArrayList of Mobile.

JSONParser.java

Java
public static ArrayList<Mobile> parseArrayFeed(JSONArray arr) {
        JSONObject obj=null;
        Mobile mobile = null;
        mMobiles.clear();
        try {

            for(int i = 0;i<arr.length();i++) {
                obj = arr.getJSONObject(i);
                mobile= new Mobile();
                mobile.setName(obj.getString("name"));
                mobile.setCompanyName(obj.getString("companyName"));
                mobile.setOperatingSystem(obj.getString("operatingSystem"));
                mobile.setProcessor(obj.getString("processor"));
                mobile.setBackCamera(obj.getString("backCamera"));
                mobile.setFrontCamera(obj.getString("frontCamera"));
                mobile.setRam(obj.getString("ram"));
                mobile.setRom(obj.getString("rom"));
                mobile.setScreenSize(obj.getString("screenSize"));
                mobile.setUrl(obj.getString("url"));
                mobile.setBattery(obj.getString("battery"));
                mMobiles.add(mobile);
            }
            return mMobiles;
        } catch (JSONException e1) {
            e1.printStackTrace();
            return null;
        }
    }
}

Open AndroidManifest.xml and put the following code, always remember to change the package name according to your company domain. We have added the android.permission.INTERNET since we will be requesting JSON Data over the network.

AndroidManifest.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidtutorialpoint.jsonparser" >
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".JSONParseActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ParseJSONArray" >
        </activity>
        <activity android:name=".ParseJSONObject" >
        </activity>
        <activity android:name=".ParseJSONArrayObject" >
        </activity>
    </application>
</manifest>

We create an activity JSONParseActivity which consist of two Buttons to decide whether to decode a JSONObject or a JSONArray as shown.

JSON Parsing Tutrial

Put the following code in JSONParseActivity:

JSONParseActivity.java

Java
package com.androidtutorialpoint.jsonparser;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class JSONParseActivity extends AppCompatActivity {

    private Button button_getJSONObject;
    private Button button_getJSONArray;
    private final String EXTRA_JSON_OBJECT_INDEX = "com.androidtutorialpoint.jsonparser";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jsonparse);
        button_getJSONObject = (Button) findViewById(R.id.button_jsonobject);
        button_getJSONArray = (Button) findViewById(R.id.button_jsonarray);


        button_getJSONObject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplication(), ParseJSONObject.class);
                i.putExtra(EXTRA_JSON_OBJECT_INDEX, 0);
                startActivity(i);

            }
        });

        button_getJSONArray.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplication(), ParseJSONArray.class);
                startActivity(i);
            }
        });
    }
}

In the above activity, we have defined setOnClickListener for the two buttons and we are calling ParseJSONObject.java and ParseJSONArray.java on clicking them respectively. Following is the Layout file for JSONParseActivity:

activity_jsonparse.xml

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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom=
    "@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:gravity="center">
    <Button
        android:id="@+id/button_jsonobject"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Parse JSONObject !!!"/>
    <Button
        android:id="@+id/button_jsonarray"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Parse JSONArray !!!"/>
</LinearLayout>

Let’s first talk about ParseJSONObject.java. This activity shows the details of the mobile retrieved from the MobileJSONObject URL and shows all the specs of the mobile along with the image. Create a Java Class ParseJSONObject.java and paste the following code.

ParseJSONObject.java

Java
package com.androidtutorialpoint.jsonparser;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

public class ParseJSONObject extends AppCompatActivity {

    private static final String TAG ="ParseJSONObject";
    private final String EXTRA_JSON_OBJECT_INDEX = "com.androidtutorialpoint.jsonparser";

    private Mobile mMobile;
    private TextView nameTextView;
    private TextView companyNameTextView;
    private TextView operatingSystemTextView;
    private TextView processorTextView;
    private TextView ramTextView;
    private TextView romTextView;
    private TextView frontCameraTextView;
    private TextView backCameraTextView;
    private TextView screenSizeTextView;
    private TextView batteryTextView;
    private ImageView photoImageView;
    private String photoUrl;

    String url = "http://androidtutorialpoint.com/api/MobileJSONObject.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parsejsonobject);

        nameTextView =(TextView)findViewById(R.id.edit_text_name);
        companyNameTextView =(TextView)findViewById(R.id.edit_text_company_name);
        operatingSystemTextView =(TextView)findViewById(R.id.edit_text_operating_system);
        processorTextView = (TextView)findViewById(R.id.edit_text_processor);
        ramTextView = (TextView)findViewById(R.id.edit_text_ram);
        romTextView = (TextView)findViewById(R.id.edit_text_rom);
        frontCameraTextView = (TextView)findViewById(R.id.edit_text_front_camera);
        backCameraTextView = (TextView)findViewById(R.id.edit_text_back_camera);
        screenSizeTextView = (TextView)findViewById(R.id.edit_text_screen_size);
        batteryTextView = (TextView)findViewById(R.id.edit_text_battery);
        photoImageView = (ImageView)findViewById(R.id.image_view_mobile_picture);



        final   ProgressDialog pDialog = new ProgressDialog(ParseJSONObject.this);
                pDialog.setMessage("Loading...");
                pDialog.show();

        JsonObjectRequest jsonObjReq = 
        new JsonObjectRequest(Method.GET,url, null,new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject response) {

                                mMobile = JSONParser.parseFeed(response);


                                nameTextView.setText
                                ("Name :" + mMobile.getName());
                                companyNameTextView.setText
                                ("Company :" + mMobile.getCompanyName());
                                operatingSystemTextView.setText
                                (" OS :" + mMobile.getOperatingSystem());
                                processorTextView.setText
                                ("Processor :" + mMobile.getProcessor());
                                ramTextView.setText
                                ("RAM :"+mMobile.getRam());
                                romTextView.setText
                                ("Memory :"+mMobile.getRom());
                                frontCameraTextView.setText
                                ("Front Camera :"+mMobile.getFrontCamera());
                                backCameraTextView.setText
                                ("Rear Camera :"+mMobile.getBackCamera());
                                screenSizeTextView.setText
                                ("Screen Size :"+mMobile.getScreenSize());
                                batteryTextView.setText
                                ("Battery :"+mMobile.getBattery());
                                photoUrl = (mMobile.getUrl());

                                ImageLoader imageLoader = 
                                new ImageLoader(Volley.newRequestQueue(getApplicationContext()),
                                        new LruBitmapCache());

                                // If you are using normal ImageView
                                imageLoader.get(photoUrl, new ImageLoader.ImageListener() {

                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                        Log.e(TAG, "Image Load Error: " + 
                                        error.getMessage());
                                    }

                                    @Override
                                    public void onResponse
                                    (ImageLoader.ImageContainer response, boolean arg1) {
                                        if (response.getBitmap() != null) {
                                            // load image into imageview
                                            photoImageView.setImageBitmap(response.getBitmap());
                                            pDialog.hide();

                                        }
                                    }
                                });

                                Log.d(TAG, response.toString());
                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        // hide the progress dialog
                        pDialog.hide();
                    }
                });

                   // Adding request to request queue
           Volley.newRequestQueue(getApplicationContext()).add(jsonObjReq);
        }
    }

The code is very simple.

  1. We are referencing the layout elements in the OnCreate() method.
  2. Then, we are submitting a network request using Volley Library to get the JSON response from the URL.
  3. On getting the response from the network request, we are calling the JSON Parser and then setting the values for the TextView and ImageView widget.

The layout for the above activity is as follows:

activity_parsejsonobject.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" >
<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:orientation="vertical"
    android:scrollbars="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"  
    tools:context=".MainActivity"
    android:gravity="center">
    <ImageView
        android:id="@+id/image_view_mobile_picture"
        android:layout_width="200dp"
        android:layout_height="200dp" />
    <TextView
        android:id="@+id/edit_text_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Model :"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:id="@+id/edit_text_company_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Company :"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:id="@+id/edit_text_operating_system"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="OS :"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:id="@+id/edit_text_processor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Processor :"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:id="@+id/edit_text_ram"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="RAM  :"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:id="@+id/edit_text_rom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Memory :"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:id="@+id/edit_text_front_camera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Front Camera :"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:id="@+id/edit_text_back_camera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Rear Camera :"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:id="@+id/edit_text_screen_size"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Screen Size :"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        />
    <TextView
        android:id="@+id/edit_text_battery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Battery :"
        android:layout_marginTop="16dp"
        android:layout_centerHorizontal="true"
        />
</LinearLayout>
</ScrollView>

Layout is also pretty simple. We have LinearLayout enclosed within a ScrollView to allow scrolling. We have an ImageView and some TextView‘s as a child of the LinearLayout to show info about Mobile.
Next, create a Java class ParseJSONArray to host a Fragment that will list the mobile phones from JSON Array URL. Put the following code in it:

ParseJSONArray.java

Java
package com.androidtutorialpoint.jsonparser;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
public class ParseJSONArray extends AppCompatActivity {
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parsejsonarray);
        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
        if (fragment == null) {
            fragment = new ListMobiles();
            fm.beginTransaction()
                    .add(R.id.fragmentContainer, fragment)
                    .commit();
        }
    }
}

Create a layout resource file for ParseJsonArray activity. It consists of just a FrameLayout that will act as a container for the Fragment.

activity_parsejsonarray.xml

 

XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragmentContainer"
    android:paddingBottom="50dp"
/>

Create a Java class ListMobiles that will display the list of mobiles.

ListMobiles.java

Java
package com.androidtutorialpoint.jsonparser;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import java.util.ArrayList;

public class ListMobiles extends ListFragment {

    private final String TAG = "ListMobiles";
    private ArrayList<Mobile>  mMobileList;
    String url = "http://androidtutorialpoint.com/api/MobileJSONArray.json";
    private final String EXTRA_JSON_OBJECT = "mobileObject";

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        final   ProgressDialog pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading...");
        pDialog.show();

        JsonArrayRequest jsonArrayReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        Log.d(TAG,response.toString());
                        Log.d(TAG,"Len "+response.length());
                        mMobileList = JSONParser.parseArrayFeed(response);

                        pDialog.hide();
                        MobileAdapter adapter = new MobileAdapter(mMobileList);
                        setListAdapter(adapter);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                // hide the progress dialog
                pDialog.hide();
            }
        });
        // Adding request to request queue
        Volley.newRequestQueue(getActivity()).add(jsonArrayReq);
    }

    private class MobileAdapter extends ArrayAdapter<Mobile> {
        public MobileAdapter(ArrayList<Mobile> mobiles) {
            super(getActivity(), 0, mobiles);
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
                // If we weren't given a view, inflate one

            Log.d(TAG,"pos "+position);
            if (convertView == null) {
                convertView = getActivity().getLayoutInflater()
                        .inflate(R.layout.category_list_item_1, null);
            }
               Mobile c = mMobileList.get(position);
            TextView nameTextView =
                        (TextView) convertView.findViewById(R.id.textview_name);
                nameTextView.setText(c.getName());

            nameTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent i = new Intent(getActivity(),ParseJSONArrayObject.class);
                    Bundle args = new Bundle();
                    //args.putSerializable(EXTRA_JSON_MOBILE_OBJECT, mMobileList.get(position));
                    i.putExtra(EXTRA_JSON_OBJECT, mMobileList.get(position));
                    startActivity(i);
                }
            });
            return convertView;
        }
    }
}

In the above code, we have created a custom ArrayAdapter for listing Mobiles:

  1. First, we Override getView() method, in which we inflate category_list_item_1.xml file which we will be showing soon. Then, we get Mobile item at corresponding position from the mMobileList and return the View.
  2. We have also created an OnClickListener that will start the ParseJSONArrayObject class and pass it the mobile phone you have clicked. We will be talking about this class shortly.
  3. In the onCreate method, we do a Network request through Volley Library to get the JSONArray Request from the JSONArray URL.On receiving the response, we parse it to get MobileList and then set the MobileAdapter on it.

We will be inflating the following layout to show the entries. So create a layout resource file category_list_item_1.xml. To avoid complexity, we have kept this layout and we are just using a TextView inside a LinearLayout.

category_list_item_1.xml

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:orientation="vertical"
    android:gravity="center">
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:padding="10dp"
        android:id="@+id/textview_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
    ></TextView>
</LinearLayout>

Now, let’s talk about the ParseJSONArrayObject class which gets called on clicking an item in the MobileList. Create a Java class ParseJSONArrayObject and put the following code.

ParseJSONArrayObject.java

Java
package com.androidtutorialpoint.jsonparser;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class ParseJSONArrayObject extends AppCompatActivity{
    private static final String TAG ="ParseJSONObject";
    private Mobile mMobile;
    private TextView nameTextView;
    private TextView companyNameTextView;
    private TextView operatingSystemTextView;
    private TextView processorTextView;
    private TextView ramTextView;
    private TextView romTextView;
    private TextView frontCameraTextView;
    private TextView backCameraTextView;
    private TextView screenSizeTextView;
    private TextView batteryTextView;
    private ImageView photoImageView;
    private String photoUrl;
    private final String EXTRA_JSON_OBJECT = "mobileObject";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parsejsonobject);
        mMobile = (Mobile)getIntent().getSerializableExtra(EXTRA_JSON_OBJECT);
        nameTextView =(TextView)findViewById(R.id.edit_text_name);
        companyNameTextView =(TextView)findViewById(R.id.edit_text_company_name);
        operatingSystemTextView =(TextView)findViewById(R.id.edit_text_operating_system);
        processorTextView = (TextView)findViewById(R.id.edit_text_processor);
        ramTextView = (TextView)findViewById(R.id.edit_text_ram);
        romTextView = (TextView)findViewById(R.id.edit_text_rom);
        frontCameraTextView = (TextView)findViewById(R.id.edit_text_front_camera);
        backCameraTextView = (TextView)findViewById(R.id.edit_text_back_camera);
        screenSizeTextView = (TextView)findViewById(R.id.edit_text_screen_size);
        batteryTextView = (TextView)findViewById(R.id.edit_text_battery);
        photoImageView = (ImageView)findViewById(R.id.image_view_mobile_picture);
        final ProgressDialog pDialog = new ProgressDialog(ParseJSONArrayObject.this);
        pDialog.setMessage("Loading...");
        pDialog.show();
                        nameTextView.setText
                        ("Name :" + mMobile.getName());
                        companyNameTextView.setText
                        ("Company :" + mMobile.getCompanyName());
                        operatingSystemTextView.setText
                        (" OS :" + mMobile.getOperatingSystem());
                        processorTextView.setText
                        ("Processor :" + mMobile.getProcessor());
                        ramTextView.setText("RAM :"+mMobile.getRam());
                        romTextView.setText
                        ("Memory :"+mMobile.getRom());
                        frontCameraTextView.setText
                        ("Front Camera :"+mMobile.getFrontCamera());
                        backCameraTextView.setText
                        ("Rear Camera :"+mMobile.getBackCamera());
                        screenSizeTextView.setText
                        ("Screen Size :"+mMobile.getScreenSize());
                        batteryTextView.setText
                        ("Battery :"+mMobile.getBattery());
                        photoUrl = (mMobile.getUrl());
                        ImageLoader imageLoader = 
                        new ImageLoader(Volley.newRequestQueue(getApplicationContext()),
                                new LruBitmapCache());
                        imageLoader.get(photoUrl, new ImageLoader.ImageListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.e(TAG, "Image Load Error: " + error.getMessage());
                            }
                            @Override
                            public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
                                if (response.getBitmap() != null) {
                                    // load image into imageview
                                    photoImageView.setImageBitmap(response.getBitmap());
                                    pDialog.hide();
                                }
                            }
                        });
    }
}

This activity is similar to ParseJSONObject activity, however here we are receiving the Mobile Object in a Bundle.
In the onCreate method:

  1. We extract the Mobile Object from the intent.
  2. Reference the Layout elements from the Layout.
  3. Finally, we set the TextView and create a network request for setting the ImageView.

Additionally, create the new Java class LruBitmapCache.java. This class is used as cache for Image Loader in Volley.

LruBitmapCache.java

Java
package com.androidtutorialpoint.jsonparser;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruBitmapCache extends LruCache<String, Bitmap> implements
        ImageCache {
    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        return cacheSize;
    }

    public LruBitmapCache() {
        this(getDefaultLruCacheSize());
    }

    public LruBitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}

Now run the app on an Android Device or an Emulator. Do remember to turn on the Internet using Wifi or mobile data, since we have not added any logic to Check for Internet Connection in our Android app.

And that’s pretty much it. We hope now you get the complete idea of JSON Parsing in Android. Please comment if you have any doubts or suggestions.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)