JSon Example in Android

9

This example explains how to handle JSon parser. It shows how to read and write data to and from a JSon file.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it JSonExample.

2.) Write following into main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical" android:layout_width="fill_parent"  
    android:layout_height="fill_parent">  
    <TextView android:layout_width="fill_parent"  
        android:layout_height="wrap_content" android:id="@+id/result" />  
</LinearLayout>

3.) Put INTERNET permission to manifest file:

4.) Run for output.

Steps:

1.) Create a project named JSonExample and set the information as stated in the image.

Build Target: Android 4.0
Application Name: JSonExample
Package Name: com. example. JSonExample
Activity Name: JSonExampleActivity
Min SDK Version: 14

2.) Open JSonExampleActivity.java file and write following code there:

package com.example.jsonexample;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;

public class JSonExampleActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        StrictMode.setThreadPolicy(
				new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
		writeJSON();
        String readTwitterFeed = readTwitterFeed();
		try {
			JSONArray jsonArray = new JSONArray(readTwitterFeed);
			Log.i(JSonExampleActivity.class.getName(),
					"Number of entries " + jsonArray.length());
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				Log.i(JSonExampleActivity.class.getName(), jsonObject.getString("text"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String readTwitterFeed() {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(
				"http://twitter.com/statuses/user_timeline/vogella.json");
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e(JSonExampleActivity.class.toString(), "Failed to download file");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}
   public void writeJSON() {
    	JSONObject object = new JSONObject();
    	try {
    		object.put("name", "EDUMobile");
    		object.put("score", new Integer(200));
    		object.put("current", new Double(152.32));
    		object.put("nickname", "Android Tutor");
    	} catch (JSONException e) {
    		e.printStackTrace();
    	}
    	System.out.println(object);
    }
}

3.) Compile and build the project.

Output

Did you enjoy this article?
Share
the
Love
Get Free Updates

9 Responses

  1. krishna says:

    hi ur blog is so good.

  2. cv says:

    Very good tutorial. The link from tutorial is not available anymore , so i tried your code with another link but i receive message ” Unfortunately JSonExampleActivity has stopped.
    What cased this error?

  3. hassan gillani says:

    thanks alot excellent work ….keep it up :-)

  4. gunaseelan says:

    Can you give us a source code in android which reads a json file from the local disk and manipulate in a list view.?

  5. gunaseelan says:

    Please reply me

  6. Tanaya says:

    Hi i want to link android to mysql database thr netbeans, wil u please help me

  7. trubi says:

    What is the difference between algorithm and steps. If the steps are what you have to do, where do you create main.xml?

  8. fdous says:

    very nice blog. U are great!!

  9. Bhadresh says:

    I read your blog but there is one confusion that what is strict mode
    “StrictMode.setThreadPolicy(
    new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());

Leave a Reply


eight − 7 =

Proudly designed by Theme Junkie.