Simple JSON Parsing Example in Android – Part II

In this blog post, ill show you how to Retrieving JSON data and Displaying it in Android TextView.

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


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://geeks.gallery/android/android_json_demo_example.php";
String name, version;
TextView tv1;

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

new JSONParse().execute();
}

private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
tv1 = (TextView) findViewById(R.id.textView1);

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

@Override
protected JSONObject doInBackground(String... args) {
JsonParser jParser = new JsonParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}

@Override
protected void onPostExecute(JSONObject json) {
try {
pDialog.dismiss();
name = json.getString("name");
version = json.getString("version");
tv1.setText(name + " - " + version);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JsonParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JsonParser() {
}

public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}

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" >

<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.geeks.gallery.json_demoexample"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

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

ScreenShot:

Screenshot_2015-01-11-13-54-24

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 *