Simple JSON Parsing Example in Android – Part IV

In this blog post, ill show you how to Retrieving Complex JSON data.

My Other blog post on JSON Tutorial.

  1. Part I – What is JSON and how to code JSON data on Php
  2. Part II – How to retrieve a simplest JSON data in Android
  3. Part III – How to retrieve a JSON data to ListView in Android
  4. Part IV – How to retrieve a complex typed JSON data in Android
  5. Part V – How to retrieve a JSON data from a Secured Site with Basic Authentication
  6. Part VI – How to Pass a JSON data to Php as a Parameters

 

Please read Part I of this blog, there you can create JSON data in php. I’m using Example 4 from that blog in this tutorial for making this blog to be simple. Hope you have created JSON data in php, so lets get started with retrieving in Android.

Step 1: Create a new project File -> Android Project. While creating a new project give activity name as MainActivity and copy paste this code.


package com.skholingua.android.retrieving_complex_json_data;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
/** Called when the activity is first created. */

private static String url = "http://serviceapi.skholingua.com/open-feeds/complex_json.php";
String name, version;
TextView outputText;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

new JSONParse().execute();
}

private class JSONParse extends AsyncTask<String, Void, String> {
private ProgressDialog pDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
outputText = (TextView) findViewById(R.id.textView1);

pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
outputText.setText("Getting Values Pls wait..");
}

@Override
protected String doInBackground(String... args) {
StringBuilder sb = new StringBuilder();
String content = MyHttpURLConnection.getData(url);
try {
JSONObject obj = new JSONObject(content);
JSONObject result = obj.getJSONObject("Owner Info");
sb.append("Name : " + result.getString("Name") + "\n");
sb.append("DOB : " + result.getString("DOB") + "\n");
sb.append("Gender : " + result.getString("Gender") + "\n");
sb.append("Website : " + obj.getString("Website") + "\n");
JSONArray people = obj.getJSONArray("Content");
for (int i = 0; i < people.length(); i++) {
JSONObject p = (JSONObject) people.get(i);
sb.append(i + 1 + " content : " + p.getString("content")
+ "\n");
sb.append("webpage : " + p.getString("webpage") + "\n");
}

return sb.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String result) {
pDialog.dismiss();
outputText.setText(result);
}
}
}

Step 2: Create a new class, MyHttpURLConnection.java and copy paste this code.


package com.skholingua.android.retrieving_complex_json_data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyHttpURLConnection {

public static String getData(String uri) {

BufferedReader reader = null;

try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setDoInput(true);
con.connect();
InputStream is = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String data = null;
String webPage = "";
while ((data = reader.readLine()) != null) {
webPage += data + "\n";
}
return webPage;

} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
}

Step 3: Open your activity_main.xml and copy paste this code:


<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.skholingua.android.retrieving_complex_json_data.MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Step 4: Open your AndroidManifest.xml and add Internet Permission.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.skholingua.android.retrieving_complex_json_data"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />

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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>

ScreenShots:

Screenshot_2015-04-06-12-01-20 Screenshot_2015-04-06-12-17-00


Tips to Remember always:


JSONObject obj = new JSONObject(content);
JSONObject result = obj.getJSONObject("Owner Info");
sb.append("Name : " + result.getString("Name") + "\n");
sb.append("DOB : " + result.getString("DOB") + "\n");
sb.append("Gender : " + result.getString("Gender") + "\n");
sb.append("Website : " + obj.getString("Website") + "\n");
JSONArray people = obj.getJSONArray("Content");
for (int i = 0; i < people.length(); i++) {
JSONObject p = (JSONObject) people.get(i);
sb.append(i + 1 + " content : " + p.getString("content")
+ "\n");
sb.append("webpage : " + p.getString("webpage") + "\n");
}

return sb.toString();

To retrieve any complex typed data, first try to get the main Object or Array which ever data it is in.

JSONObject obj = new JSONObject(content);

Now, when next data is either object or Array, use the above the object and retrieve it.

JSONObject result = obj.getJSONObject("Owner Info");

Now, as per my example, now i can retrieve data using above object.


sb.append("Name : " + result.getString("Name") + "\n");
sb.append("DOB : " + result.getString("DOB") + "\n");
sb.append("Gender : " + result.getString("Gender") + "\n");

If you notice now, my next data is a Json data of main Object rather than sub-Object(i.e result Object). so i used the main Object to retrieve it.


sb.append("Website : " + obj.getString("Website") + "\n");

Next is JsonArray with a list of multiple Json data and its belong to main Object, so i used for-loop to retrieve it.


JSONArray people = obj.getJSONArray("Content");
for (int i = 0; i < people.length(); i++) {
JSONObject p = (JSONObject) people.get(i);
sb.append(i + 1 + " content : " + p.getString("content")
+ "\n");
sb.append("webpage : " + p.getString("webpage") + "\n");
}


Hope this helpful. Your valuable comments are always welcomed. It will help to improve my post and understanding.

Download Source Code from here.

durga chiranjeevi

durga chiranjeevi

I'm currently working as Android developer at Energy Alternatives India. Interested in Application and Game development.
durga chiranjeevi
Comments
  1. omid

Leave a Reply

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