Thursday, 5 December 2013

REST+JSON Web service Example in Android.

Download this project-->REST+JSONWebserviceExample.zip
output:

activity_main.xml:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/ScrollView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

</ScrollView>

MainActivity.java:
package com.ram.restjsonwebserviceexample;

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

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;

@SuppressLint("NewApi")
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.cheesejedi.com/rest_services/get_big_cheese.php?puzzle=");
TextView textView = (TextView) findViewById(R.id.textView1);
try {

HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();

JSONArray jsonArray = new JSONArray(jsonResult);

for (int i = 0; i < jsonArray.length(); i++) {
textView.append("id: "
+ jsonArray.getJSONObject(i).getString("id").toString()
+ "\n");
textView.append("level: "
+ jsonArray.getJSONObject(i).getString("level")
.toString() + "\n");
textView.append("time_in_secs: "
+ jsonArray.getJSONObject(i).getString("time_in_secs")
.toString() + "\n");
textView.append("par: "
+ jsonArray.getJSONObject(i).getString("par")
.toString() + "\n");
textView.append("initials: "
+ jsonArray.getJSONObject(i).getString("initials")
.toString() + "\n");
textView.append("quote: "
+ jsonArray.getJSONObject(i).getString("quote")
.toString() + "\n");
textView.append("time_stamp: "
+ jsonArray.getJSONObject(i).getString("time_stamp")
.toString() + "\n");
textView.append("-------------------------------------------------"
+ "\n");

}

// textView.setText(jsonResult);

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();

InputStreamReader isr = new InputStreamReader(is);

BufferedReader rd = new BufferedReader(isr);

try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}

catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}


AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ram.restjsonwebserviceexample"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <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="com.ram.restjsonwebserviceexample.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>