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>
<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
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 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 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;
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(
newStrictMode.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();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.setThreadPolicy(
newStrictMode.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);
}
}
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
Thanks
akm
www.cdacians.com
No comments:
Post a Comment