Thursday, November 1, 2012

Android PHP JSON tutorial

Here I'm going to demonstrate how we can decode JSON encoded data in Android using very simple example. I used Android 2.2 for this.

First here is some extra information about JSON:

1. What is JSON

  • JSON stands for JavaScript Object Notation
  • JSON is lightweight text-data interchange format
  • JSON is language independent 
  • JSON is "self-describing" and easy to understand
                                                           (from w3schools)  
2. Click here to know benefits of JSON over XML

Now let's see simple example of JSON reading in Android.
In my project there is a PHP web service which encodes a string array in to JSON format. I'm going to access that web service using Android http client and then it decodes json data. I have tested this on Android 2.2

1. Here is the code for PHP

<?php
$data = array('name' => 'Froyo', 'version' => 'Android 2.2'); 
print (json_encode($data)); 
?> 

2. Contents of Android Layout Manifest and Activity files
 main.xml file
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="216dp"
        android:layout_height="36dp"
        android:layout_weight="1"
        android:layout_x="66dp"
        android:layout_y="192dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</AbsoluteLayout>

manifest.xml 
You need to add internet permissions 
 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.json.php"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".JSONExampleActivity"
            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>

Android activity 

package com.json.php;

import android.app.Activity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.TextView;
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.JSONException;
import org.json.JSONObject;


public class JSONExampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://codeincloud.tk/json_android_example.php");
        TextView textView = (TextView)findViewById(R.id.textView1);
  try {
   
   HttpResponse response = httpclient.execute(httppost);
   String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
   JSONObject object = new JSONObject(jsonResult);

   String name = object.getString("name");
      String verion = object.getString("version");
      textView.setText(name + " - " + verion);
      
  } 
  catch (JSONException e) {
   e.printStackTrace();
  } 
  catch (ClientProtocolException e) {
   e.printStackTrace();
  } 
  catch (IOException e) {
   e.printStackTrace();
  }


       }
    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
         
        try {
         while ((rLine = rd.readLine()) != null) {
          answer.append(rLine);
           }
        }
         
        catch (IOException e) {
            e.printStackTrace();
         }
        return answer;
       }
}

 Result

Click here to download the Android project.

That's it
 Happy coding! :)

25 comments:

  1. No matter if some one searches for his necessary thing,
    so he/she needs to be available that in detail, so that thing is maintained over here.
    My homepage how to lose weight fast for kids for free

    ReplyDelete
  2. This article presents clear idea in support of the new users of blogging, that genuinely how to do blogging.
    Here is my web blog :: nab internet banking

    ReplyDelete
  3. This article presents clear idea in support of the new users of blogging, that
    genuinely how to do blogging.
    My page - nab internet banking

    ReplyDelete
  4. I take pleasure in, lead to I found just what I
    was having a look for. You have ended my 4 day long hunt!
    God Bless you man. Have a great day. Bye
    Also visit my blog post - news

    ReplyDelete
  5. NICE BLOG!!! Thanks for sharing useful information about FNT Softwre Solutions and being one of best Software Training institute in Bangalore we agree that this blog is very useful for the students are Searching for best software courses, I would really like to come back again right here for like wise good articles or blog posts. Thanks for sharing...PHP Training Bangalore .

    ReplyDelete
  6. Am running the same code you have given by for me unfortunately has stopped. How can i rectify it. I dont know to identify error from logcat too. Any help

    ReplyDelete
  7. Am using the above code exactly but when i run it am getting run time error, unfortunately has stopped. How can i clear this can anyone help me.

    ReplyDelete
  8. Hi, nice description.Thanks for your help..

    -Aparna
    Theosoft

    ReplyDelete
  9. hi..Im college student, thanks for sharing :)

    ReplyDelete
  10. You've helped many newbies like me who was searching for this simple concept but never succeed to implement it.This tutorial is so simple and understandable that it ended my search for Json Parsing the moment it worked for me.Thanks a lot. Keep up the good work.(y)

    ReplyDelete
  11. You've helped many newbies like me who was searching for this simple concept but never succeed to implement it.This tutorial is so simple and understandable that it ended my search for Json Parsing the moment it worked for me.Thanks a lot. Keep up the good work.(y)

    ReplyDelete
  12. Peluang Bisnis Dahsyat Yusuf Mansur. "Orang islam harus KAYA"
    dan "Beli Kembali Aset Indonesia" dengan INDONESIA BERJAMAAH
    Segera Amankan Posisi Anda, Segera JOIN bersama
    Komunitas VSI , bisnis terbaru Ustadz Yusuf Mansur
    Dengan Produk V-pay ( Virtual Payment ) Anda akan
    dimudahkan dalam hal urusan pembayaran listrik,
    telpon, pulsa, PDAM, TV Berbayar, Internet, Asuransi,
    Kartu Kredit dan lain-lain. Transaksi dapat dilakukan
    melalui Website, SMS, Android, BlackBerry, iPhone dan YM.
    Penasaran Dengan Bisnis Ustd. Yusuf Mansur ini Kunjungi Website: KLIK DISINI

    ReplyDelete
  13. think your blog is pretty good which have some useful information. Thanks for sharing us!


    -------------------------------------------------------------------------------
    iPhone App Development :: && :: Mobile and Web Application Development

    ReplyDelete
  14. Am running the same code you have given by for me unfortunately has stopped. How to fix this code.

    ReplyDelete
  15. Am using the above code exactly but when i run it am getting run time error, unfortunately has stopped. How to solve this problem

    ReplyDelete
  16. Nice blog...Very useful information is providing by ur blog..here is a way to find

    Php training institute in bangalore

    ReplyDelete
  17. Nice blog...Very useful information is providing by ur blog. find php tutorials Very clear and helpful for beginners.

    ReplyDelete
  18. Thanks for Sharing the information. It is helpful in real sense.
    Regards
    Pi Technologies
    SMO Company in Indore

    ReplyDelete
  19. Nicely presented information in this post, I prefer to read this kind of stuff. The quality of content is fine and the conclusion is good. Thanks for the post. forgings manufacturing

    ReplyDelete
  20. Thank you for this helpful tutorial that will help new trainee at Mobile App Development Company in India

    ReplyDelete
  21. Thank you for sharing; it’s nice and helpful information. I hope I could read more information like this in the next visit.
    regards,
    SEO melbourne

    ReplyDelete