Tuesday, October 30, 2012

android parse json response from php url

Create a PHP file to return JSON output from an array. Then create android activity and a java file to navigate to the URL and get the response from the PHP URL to implement into your page. Make sure to use your system IP instead of localhost or 127.0.0.1. Your code will be running on the emulator (a separate device from your machine) which will not identify the localhost. So you have to make sure to keep your IP in your URL. This will solve your "java.net.ConnectException: localhost/127.0.0.1:80 - Connection refused" issue in android. Also make sure to include the below line into your androidmanifest.xml file "
 <uses-permission android:name="android.permission.INTERNET" />  
" This will solve you the "java.net.SocketException: Permission denied" issue.
List.php
 <?php  
 $lst = array("1"=>"aa", "2"=>"bb", "3"=>"cc");  
 echo json_encode($lst);  
 ?>  
SampleJson.java
 package com.navigation.samplenavigation;  
 import java.io.IOException;  
 import org.json.JSONArray;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import android.app.Activity;  
 import android.content.Intent;  
 import android.os.Bundle;  
 import android.view.Menu;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.EditText;  
 import android.widget.Toast;  
 import com.navigation.samplenavigation.R.id;  
 public class SampleNavigationActivity extends Activity {  
       // contacts JSONArray  
   JSONArray contacts = null;  
   @Override  
   public void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_sample_navigation);  
     final Button button = (Button) findViewById(id.submit);  
     button.setOnClickListener(new View.OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                     // TODO Auto-generated method stub                                          
                     JSONObject json = null;  
                     try {                                
 json = JsonReader.readJsonFromUrl("http://10.91.28.56/php/jsonreturn/list.php");  
                     } catch (IOException e) {  
                          // TODO Auto-generated catch block  
                          e.printStackTrace();  
                     } catch (JSONException e) {  
                          // TODO Auto-generated catch block  
                          e.printStackTrace();  
                     }  
                     System.out.println(json.toString());  
                     try {  
                          System.out.println(json.get("1"));  
                     } catch (JSONException e) {  
                          // TODO Auto-generated catch block  
                          e.printStackTrace();  
                     }                      
                }  
           });  
   }  
   @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
     getMenuInflater().inflate(R.menu.activity_sample_navigation, menu);  
     return true;  
   }    
 }  
JsonReader.java
 package com.navigation.samplenavigation;  
 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.InputStreamReader;  
 import java.io.Reader;  
 import java.net.URL;  
 import java.nio.charset.Charset;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 public class JsonReader {  
  private static String readAll(Reader rd) throws IOException {        
   StringBuilder sb = new StringBuilder();  
   int cp;  
   while ((cp = rd.read()) != -1) {  
    sb.append((char) cp);  
   }  
   return sb.toString();  
  }  
  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {        
   InputStream is = new URL(url).openStream();  
   try {         
    BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));     
    String jsonText = readAll(rd);     
    JSONObject json = new JSONObject(jsonText);  
    return json;  
   } finally {  
    is.close();  
   }  
  }   
 }