Android JSON Parsing Tutorial

Similar documents
Android Volley Tutorial

Android CardView Tutorial

Android - JSON Parser Tutorial

Fragment Example Create the following files and test the application on emulator or device.

<uses-permission android:name="android.permission.internet" />

Android Navigation Drawer for Sliding Menu / Sidebar

MAD ASSIGNMENT NO 3. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Switching UIs

M.A.D ASSIGNMENT # 2 REHAN ASGHAR BSSE 15126

Tabel mysql. Kode di PHP. Config.php. Service.php

CSE 660 Lab 7. Submitted by: Arumugam Thendramil Pavai. 1)Simple Remote Calculator. Server is created using ServerSocket class of java. Server.

Tip Calculator. xmlns:tools=" android:layout_width="match_parent"

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Managing Screen Orientation

LAMPIRAN. byte bcdtodec(byte val) { return( (val/16*10) + (val%16) ); } void setup() {

Basic GUI elements - exercises

Mobile Application Development Lab [] Simple Android Application for Native Calculator. To develop a Simple Android Application for Native Calculator.

CSE 660 Lab 3 Khoi Pham Thanh Ho April 19 th, 2015

Create a local SQL database hosting a CUSTOMER table. Each customer includes [id, name, phone]. Do the work inside Threads and Asynctasks.

SMAATSDK. NFC MODULE ON ANDROID REQUIREMENTS AND DOCUMENTATION RELEASE v1.0

Intents. Your first app assignment

<uses-permission android:name="android.permission.internet"/>

LAMPIRAN PROGRAM. public class ListArrayAdapterPost extends ArrayAdapter<ModelDataPost> {

PROGRAMMING APPLICATIONS DECLARATIVE GUIS

EMBEDDED SYSTEMS PROGRAMMING UI Specification: Approaches

Android development. Outline. Android Studio. Setting up Android Studio. 1. Set up Android Studio. Tiberiu Vilcu. 2.

android:layout_margintop="5dp" > <EditText android:layout_width="210dp"

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

Arrays of Buttons. Inside Android

Android Workshop: Model View Controller ( MVC):

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 2

EMBEDDED SYSTEMS PROGRAMMING Application Basics


Fragments. Lecture 11

Practical 1.ListView example

LAMPIRAN PROGRAM. public class Listdata_adiktif extends ArrayAdapter<ModelData_adiktif> {

PENGEMBANGAN APLIKASI PERANGKAT BERGERAK (MOBILE)

Android Application Model I

Android UI Development

Vienos veiklos būsena. Theory

Mobile Computing Fragments

EMBEDDED SYSTEMS PROGRAMMING Android Services

Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Cloudant NoSQL DB)

Android SQLite Database Tutorial - CRUD Operations

Android Application Model I. CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr.

COMP61242: Task /04/18

Create Parent Activity and pass its information to Child Activity using Intents.

Coding Menggunakan software Eclipse: Mainactivity.java (coding untuk tampilan login): package com.bella.pengontrol_otomatis;

Creating a Custom ListView


MAD ASSIGNMENT NO 2. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

Manifest.xml. Activity.java

Software Practice 3 Before we start Today s lecture Today s Task Team organization

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Mobile Software Development for Android - I397

LifeStreet Media Android Publisher SDK Integration Guide

StoppUhr. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="start1"

Android Basics. Android UI Architecture. Android UI 1

Android Coding. Dr. J.P.E. Hodgson. August 23, Dr. J.P.E. Hodgson () Android Coding August 23, / 27

Android - Widgets Tutorial

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering

Appendix A : Android Studio Code For Android

Android Layout Types

Android/Java Lightning Tutorial JULY 30, 2018

Chapter 8 Positioning with Layouts

Java & Android. Java Fundamentals. Madis Pink 2016 Tartu

When programming in groups of people, it s essential to version the code. One of the most popular versioning tools is git. Some benefits of git are:

Produced by. Mobile Application Development. Eamonn de Leastar

Introduction. Who Should Read This Book. Key Topics That This Book Covers

Getting Started With Android Feature Flags

Agenda. Overview of Xamarin and Xamarin.Android Xamarin.Android fundamentals Creating a detail screen

package import import import import import import import public class extends public void super new this class extends public super public void new

User Interface Development in Android Applications

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Wireless Vehicle Bus Adapter (WVA) Android Library Tutorial

Our First Android Application

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Tutorial: Setup for Android Development

M.A.D Assignment # 1

Adapter.

EMBEDDED SYSTEMS PROGRAMMING Android NDK

1. Location Services. 1.1 GPS Location. 1. Create the Android application with the following attributes. Application Name: MyLocation

1 카메라 1.1 제어절차 1.2 관련주요메서드 1.3 제작철차 서피스뷰를생성하고이를제어하는서피스홀더객체를참조해야함. 매니페스트에퍼미션을지정해야한다.

TextView Control. EditText Control. TextView Attributes. android:id - This is the ID which uniquely identifies the control.

EMBEDDED SYSTEMS PROGRAMMING Android NDK

Dynamically Create Admob Banner and Interstitial Ads

Android Beginners Workshop

Data Persistence. Chapter 10

COMP4521 EMBEDDED SYSTEMS SOFTWARE

android-espresso #androidespresso

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

ActionBar. import android.support.v7.app.actionbaractivity; public class MyAppBarActivity extends ActionBarActivity { }

Embedded Systems Programming - PA8001

Solving an Android Threading Problem

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

Android Programs Day 5

MVC Apps Basic Widget Lifecycle Logging Debugging Dialogs


Fragments. Lecture 10

LISTING PROGRAM APLIKASI ANDROID

Transcription:

Android JSON Parsing Tutorial by Kapil - Thursday, May 19, 2016 http://www.androidtutorialpoint.com/networking/json-parsing-tutorial-android/ YouTube Video 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 required Information. To explain the concept we would be using two sample JSON responses we have created and placed at below links. http://androidtutorialpoint.com/api/mobilejsonarray.json http://androidtutorialpoint.com/api/mobilejsonobject.json 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. 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", { 1 / 22

"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 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. 2 / 22

Android provides the following classes to manipulate a JSON response : JSONObject,JSONArray, 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 given URL and then display them as a list, on Clicking each individual Mobile, details of the mobile will be displayed. (adsbygoogle = window.adsbygoogle ).push({); 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. and put following code in it. Mobile. package com.androidtutorialpoint.jsonparser; import.io.serializable; public class Mobile implements Serializable{ private String mname; private String mcompanyname; 3 / 22

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() { 4 / 22

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. package com.androidtutorialpoint.jsonparser; import org.json.jsonarray; import org.json.jsonexception; 5 / 22

import org.json.jsonobject; import.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. 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")); 6 / 22

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. 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. <? version="1.0" encoding="utf-8"?> <manifest ns: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> 7 / 22

<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. Put following code in JSONParseActivity: JSONParseActivity. 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"; 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() { 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() { 8 / 22

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. and ParseJSONArray. on clicking them respectively.following is Layout file for JSONParseActivity: activity_jsonparse. <? version="1.0" encoding="utf-8"?> <LinearLayout ns:android="http://schemas.android.com/apk/res/android" ns:tools="http://schemas.android.com/tools" android:orientation="vertical" 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:text="parse JSONObject!!!"/> <Button android:id="@+id/button_jsonarray" android:text="parse JSONArray!!!"/> </LinearLayout> Let's first talk about ParseJSONObject.. 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. and paste the following code. ParseJSONObject. 9 / 22

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"; protected void oncreate(bundle savedinstancestate) { 10 / 22

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>() { 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() { 11 / 22

public void onerrorresponse(volleyerror error) { Log.e(TAG, "Image Load Error: " + error.getmessage()); 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() { 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. 12 / 22

<? version="1.0" encoding="utf-8"?> <ScrollView android:layout_height="match_parent" ns:android="http://schemas.android.com/apk/res/android" > <LinearLayout ns:android="http://schemas.android.com/apk/res/android" ns:tools="http://schemas.android.com/tools" 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:text="model :" android:layout_margintop="16dp" android:layout_centerhorizontal="true" /> <TextView android:id="@+id/edit_text_company_name" android:text="company :" android:layout_margintop="16dp" android:layout_centerhorizontal="true" /> <TextView android:id="@+id/edit_text_operating_system" android:text="os :" android:layout_margintop="16dp" android:layout_centerhorizontal="true" /> 13 / 22

<TextView android:id="@+id/edit_text_processor" android:text="processor :" android:layout_margintop="16dp" android:layout_centerhorizontal="true" /> <TextView android:id="@+id/edit_text_ram" android:text="ram :" android:layout_margintop="16dp" android:layout_centerhorizontal="true" /> <TextView android:id="@+id/edit_text_rom" android:text="memory :" android:layout_margintop="16dp" android:layout_centerhorizontal="true" /> <TextView android:id="@+id/edit_text_front_camera" android:text="front Camera :" android:layout_margintop="16dp" android:layout_centerhorizontal="true" /> <TextView android:id="@+id/edit_text_back_camera" android:text="rear Camera :" android:layout_margintop="16dp" android:layout_centerhorizontal="true" /> <TextView android:id="@+id/edit_text_screen_size" android:text="screen Size :" android:layout_margintop="16dp" 14 / 22

android:layout_centerhorizontal="true" /> <TextView android:id="@+id/edit_text_battery" 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. 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 { 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 15 / 22

a container for the Fragment activity_parsejsonarray. <? version="1.0" encoding="utf-8"?> <FrameLayout ns:android="http://schemas.android.com/apk/res/android" 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. 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; 16 / 22

import org.json.jsonarray; import.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"; 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>() { 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() { 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); 17 / 22

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() { 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. 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..to avoid complexity we have kept this layout and we are just using a TextView inside a LinearLayout. 18 / 22

category_list_item_1. <? version="1.0" encoding="utf-8"?> <LinearLayout ns:android="http://schemas.android.com/apk/res/android" ns:tools="http://schemas.android.com/tools" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <TextView ns:android="http://schemas.android.com/apk/res/android" android:padding="10dp" android:id="@+id/textview_name" 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 class ParseJSONArrayObject and put following code. ParseJSONArrayObject. 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; 19 / 22

private TextView backcameratextview; private TextView screensizetextview; private TextView batterytextview; private ImageView photoimageview; private String photourl; private final String EXTRA_JSON_OBJECT = "mobileobject"; 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() { public void onerrorresponse(volleyerror error) { Log.e(TAG, "Image Load Error: " + error.getmessage()); public void onresponse(imageloader.imagecontainer response, boolean arg1) { if (response.getbitmap()!= null) { 20 / 22

// 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 class LruBitmapCache.. This class is used as cache for Image Loader in Volley, For more details please refer to our Volley Tutorial -> Android Volley Tutorial LruBitmapCache. 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); 21 / 22

Powered by TCPDF (www.tcpdf.org) Android JSON Parsing Tutorial - 05-19-2016 protected int sizeof(string key, Bitmap value) { return value.getrowbytes() * value.getheight() / 1024; public Bitmap getbitmap(string url) { return get(url); 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. (adsbygoogle = window.adsbygoogle ).push({); 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. PDF generated by Kalin's PDF Creation Station 22 / 22