My Blog List

Android FirstAid Coding

A Small Help From a Small Heart
Powered by Blogger.

A software professional, who still likes to code, likes to blog and loves gadgets.

Friday 18 May 2012

How to call json webservice android

Today i am going to show you how to call a webservice in android which returns data in a json format.This data will be displayed in a listview using fragment.


1.MainActivity.java

package com.example.parsejson;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle; 
public class MainActivity extends  Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     Configuration config = getResources().getConfiguration();
     FragmentManager fragmentManager = getFragmentManager();
     FragmentTransaction fragmentTransaction = 
     fragmentManager.beginTransaction();

     Myfragment pm_fragment = new Myfragment();
        fragmentTransaction.replace(android.R.id.content, pm_fragment);
     fragmentTransaction.commit();
  }
  
   

}

2.Myfragment .java

package com.example.parsejson;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class Myfragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.v("ListFragment", "onCreateView()");
Log.v("ListContainer", container == null ? "true" : "false");
Log.v("ListsavedInstanceState", savedInstanceState == null ? "true" : "false");
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.list_view, container, false);
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("ListFragment", "onCreate()");
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v("ListFragment", "onActivityCreated().");
Log.v("ListsavedInstanceState", savedInstanceState == null ? "true" : "false");

new CallAPI().execute();

}

private void displayListView(List<AddressVO> addressList) {
MyCustomAdapter adapter = new MyCustomAdapter(getActivity(), R.layout.row, addressList);
ListView listView = (ListView) getView().findViewById(R.id.listofAddress);
// Assign adapter to ListView
listView.setAdapter(adapter);

}
private class CallAPI extends AsyncTask<String, String, List<AddressVO>> {

JSONParser jsonParser = new JSONParser();
ProgressDialog dialog;
@Override
protected void onPreExecute(){
dialog = ProgressDialog.show(getActivity(), "", "Please wait...");
}

protected List<AddressVO> doInBackground(String... args) {
JSONObject json;
List<AddressVO> listItems = new ArrayList<AddressVO>();  
try {
//https://maps.googleapis.com/maps/api/geocode/json?address=bhubaneswar&sensor=true
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("address", "bhubaneswar"));
params.add(new BasicNameValuePair("sensor", "true"));
json = jsonParser.makeHttpRequest("https://maps.googleapis.com/maps/api/geocode/json", "GET", params);
//System.out.println("json=="+json);

String status = json.getString("status");
//System.out.println(status);
if (status.equals("OK")) {

JSONArray jsonArr = json.getJSONArray("results");
JSONObject jsonObject = jsonArr.getJSONObject(0);
JSONArray jsonsubArr = jsonObject.getJSONArray("address_components");
for (int i = 0;i< jsonsubArr.length();i++) {
JSONObject jsonAddressObject = jsonsubArr.getJSONObject(i);
String long_name = jsonAddressObject.getString("long_name");
String short_name = jsonAddressObject.getString("short_name");
System.out.println(long_name + ""+short_name);

AddressVO addressVO =new AddressVO();
addressVO.setLongName("Long Name : "+long_name);
addressVO.setShortName("Short Name : "+short_name);

listItems.add(addressVO);
}
}
} catch (Exception e1) {
System.out.println(e1);
}
return listItems;
}
protected void onPostExecute(List<AddressVO> addressList) {
dialog.dismiss();

displayListView(addressList);

}
}

}

3.JSONParser .java

package com.example.parsejson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
       List<NameValuePair> params) throws Exception {

   // Making HTTP request
   try {

       // check for request method
       if (method == "POST") {
           // request method is POST
           // defaultHttpClient
           DefaultHttpClient httpClient = new DefaultHttpClient();
           HttpPost httpPost = new HttpPost(url);
           httpPost.setEntity(new UrlEncodedFormEntity(params));

           // new
           HttpParams httpParameters = httpPost.getParams();
           // Set the timeout in milliseconds until a connection is
           // established.
           int timeoutConnection = 10000;
           HttpConnectionParams.setConnectionTimeout(httpParameters,
                   timeoutConnection);
           // Set the default socket timeout (SO_TIMEOUT)
           // in milliseconds which is the timeout for waiting for data.
           int timeoutSocket = 10000;
           HttpConnectionParams
                   .setSoTimeout(httpParameters, timeoutSocket);
           // new
           HttpResponse httpResponse = httpClient.execute(httpPost);
           HttpEntity httpEntity = httpResponse.getEntity();
           is = httpEntity.getContent();

       } else if (method == "GET") {
           // request method is GET
           DefaultHttpClient httpClient = new DefaultHttpClient();
           if (params != null) {
            String paramString = URLEncodedUtils.format(params, "utf-8");
           url += "?" + paramString;
}
           
           HttpGet httpGet = new HttpGet(url);
           // new
           HttpParams httpParameters = httpGet.getParams();
           // Set the timeout in milliseconds until a connection is
           // established.
           int timeoutConnection = 10000;
           HttpConnectionParams.setConnectionTimeout(httpParameters,
                   timeoutConnection);
           // Set the default socket timeout (SO_TIMEOUT)
           // in milliseconds which is the timeout for waiting for data.
           int timeoutSocket = 10000;
           HttpConnectionParams
                   .setSoTimeout(httpParameters, timeoutSocket);
           // new
           HttpResponse httpResponse = httpClient.execute(httpGet);
           HttpEntity httpEntity = httpResponse.getEntity();
           is = httpEntity.getContent();
       }

   } catch (UnsupportedEncodingException e) {
       throw new Exception("Unsupported encoding error.");
   } catch (ClientProtocolException e) {
       throw new Exception("Client protocol error.");
   } catch (SocketTimeoutException e) {
       throw new Exception("Sorry, socket timeout.");
   } catch (ConnectTimeoutException e) {
       throw new Exception("Sorry, connection timeout.");
   } catch (IOException e) {
       throw new Exception("I/O error(May be server down).");
   }
   try {
       BufferedReader reader = new BufferedReader(new InputStreamReader(
               is, "iso-8859-1"), 8);
       StringBuilder sb = new StringBuilder();
       String line = null;
       while ((line = reader.readLine()) != null) {
           sb.append(line + "\n");
       }
       is.close();
       json = sb.toString();
   } catch (Exception e) {
       throw new Exception(e.getMessage());
   }

   // try parse the string to a JSON object
   try {
       jObj = new JSONObject(json);
   } catch (JSONException e) {
       throw new Exception(e.getMessage());
   }

   // return JSON String
   return jObj;

}
}
4.MyCustomAdapter .java

package com.example.parsejson;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MyCustomAdapter extends ArrayAdapter<AddressVO>{

private Context context;
private TextView longNameTv,shortNameTv;
private List<AddressVO> webdata = new ArrayList<AddressVO>();
public MyCustomAdapter(Context context, int textViewResourceId,
List<AddressVO> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.webdata = objects;
}

public int getCount() {
return this.webdata.size();
}

public AddressVO getItem(int index) {
return this.webdata.get(index);
}

public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
// ROW INFLATION
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.row, parent, false);
}

AddressVO AddressVO = getItem(position);
longNameTv = (TextView) row.findViewById(R.id.longNameTv);
shortNameTv = (TextView) row.findViewById(R.id.shortNameTv);

longNameTv.setText(AddressVO.longName);
shortNameTv.setText(AddressVO.shortName);
return row;
}
}
 5.AddressVO .java

package com.example.parsejson;

public class AddressVO {
public String shortName,longName;

public String getShortName() {
return shortName;
}

public void setShortName(String shortName) {
this.shortName = shortName;
}

public String getLongName() {
return longName;
}

public void setLongName(String longName) {
this.longName = longName;
}
}

6.list_view.xml

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="JSON parsing content"
        android:textColor="#EA5353"
        android:textSize="20sp" />

    <ListView
        android:id="@+id/listofAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="5dp"
        android:text="rajuandroid.blogspot.com"
        android:textColor="#8853EA"
        android:textSize="20sp" />

</LinearLayout>

7.row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#CB9D9D"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/longNameTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:layout_marginLeft="5dp"
        android:paddingLeft="10dip"
        android:textColor="#000220"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/shortNameTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:paddingLeft="10dip"
        android:textColor="#000000"
        android:textSize="19sp"
        android:textStyle="bold" />

</LinearLayout>

8.manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.parsejson"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />
    <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.example.parsejson.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>




I used this (https://maps.googleapis.com/maps/api/geocode/json?address=bhubaneswar&sensor=true) API to get address detail in a JSON format.The result is looks like below








2 comments:

  1. Hi this is what i needed :)
    but i got an error it says something about "android.os NetworkOnMainThread Exception "

    how can i fix it?
    thanks :)

    ReplyDelete
    Replies
    1. Hi,
      VampCess_Hanna24

      I fixed the bug.Please follow the above code.

      Thanks,
      Rajendra

      Delete