Main navigation

Android JSON Parsing Tutorial

adsense

Pre-requisites:

  1. Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
  2. A real time android device (Smartphone or Tablet) configured with Android Studio. .

Creating 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 following code in it.

Mobile.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 function 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 attribute of the mobile object.

JSONParser.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

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 Network.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://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 following code in JSONParseActivity:

JSONParseActivity.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 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 Layout file for JSONParseActivity:

activity_jsonparse.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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

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 = "https://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. To know more about how to use Volley Library, refer to the following tutorial => Android Volley Tutorial
  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 version="1.0" encoding="utf-8"?>
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="https://schemas.android.com/apk/res/android" >
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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 following code in it:

ParseJSONArray.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 version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://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

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 = "https://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 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 version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">
<TextView xmlns:android="https://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 get’s called on clicking an item in the MobileList. Create a java class ParseJSONArrayObject and put following code.

ParseJSONArrayObject.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, For more details please refer to our Volley Tutorial -> Android Volley Tutorial

LruBitmapCache.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.



What’s Next ?

Check our other tutorial, and create cool apps. Don’t forget to subscribe our blog for latest android tutorials. Also Like our Facebook Page or Add us on Twitter.

Click on the Download Now button to download the full code.

Android Tutorial Point Download Now




Reader Interactions

Comments

Leave a Reply

Advertisment ad adsense adlogger