Android Json Processing using GSON and Display in on a ListView

This is my way to process a json request using GSON library and display it on a ListView

Connect to a WebService

the code i used to interact with the web service is based on this blog

First, download GSON library in here

Format JSON Response

the json response format which we are going to response is like this:

{"locations":[{"name":"test","description":"testse","latlng":[12.0,13.0]},{"name":"gfd","description":"hh","latlng":[15.0,16.0]},{"name":"rumah bagas","description":"iki rumahe bagas","latlng":[0.0,20.0]}]}

the Model

in the json response show that it has a locations that consist on many location.

The is the basic data from the json response:

package com.bopbi.model;

public class LocationModel {
	private String name;
	private String description;
	private float[] latlng;

	public String getName() {
		return name;
	public void setName(String name) { = name;
	public String getDescription() {
		return description;
	public void setDescription(String description) {
		this.description = description;

	public float[] getLatlng() {
		return latlng;
	public void setLatlng(float[] latlng) {
		this.latlng = latlng;

and the which the container for the LocationModel:

package com.bopbi.model;

import java.util.List;

public class LocationList {
    private List locations;

    public List getLocations() {
        return locations;
    public void setLocationList(List locations) {
        this.locations = locations;
} is the adapter that will be use to display the LocationList in a ListView is extends from an ArrayAdapter:

package com.bopbi.model;

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;

import com.bopbi.R;

public class LocationAdapter extends ArrayAdapter {

	int resource;
	String response;
    Context context;
    private LayoutInflater mInflater;

	public LocationAdapter(Context context, int resource, List objects) {
		super(context, resource, objects);
		this.resource = resource;
		mInflater = LayoutInflater.from(context);

	static class ViewHolder {
		TextView title;
		TextView description;

	public View getView(int position, View convertView, ViewGroup parent)
		ViewHolder holder;
        //Get the current location object
        LocationModel lm = (LocationModel) getItem(position);

        //Inflate the view
            convertView = mInflater.inflate(R.layout.item, null);
			holder = new ViewHolder();
			holder.title = (TextView) convertView
			holder.description = (TextView) convertView


        	holder = (ViewHolder) convertView.getTag();


		return convertView;


and here is the main file, that later will be use to call the webservice using AsyncTask and display in onn a ListView

package com.bopbi.ui;

import java.util.ArrayList;

import com.bopbi.R;
import com.bopbi.model.LocationAdapter;
import com.bopbi.model.LocationList;
import com.bopbi.model.LocationModel;
import com.bopbi.util.RestClient;
import com.bopbi.util.RestClient.RequestMethod;

import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;

public class ListRest extends Activity {
	LocationManager lm;

	ArrayList locationArray = null;
	LocationAdapter locationAdapter;
	LocationList list;

	ListView lv;
	TextView loadingText;

	public void onCreate(Bundle savedInstanceState) {

        lv = (ListView) findViewById(;

        locationArray = new ArrayList();
        locationAdapter = new LocationAdapter(ListRest.this, R.layout.item, locationArray);


		try {
			new LocationSync().execute("");
		} catch(Exception e) {}

	private class LocationSync extends AsyncTask<String, Integer, LocationList> {

		protected LocationList doInBackground(String... urls) {
			LocationList list = null;
			int count = urls.length;

	        for (int i = 0; i < count; i++) {
	        	try {

	    			RestClient client = new RestClient(urls[i]);

	    			try {
	    			} catch (Exception e) {

	    			String json = client.getResponse();

	    			list = new Gson().fromJson(json, LocationList.class);

	    		} catch(Exception e) {}
	        return list;

		protected void onProgressUpdate(Integer... progress) {


	    protected void onPostExecute(LocationList loclist) {

	    	for(LocationModel lm : loclist.getLocations())


Layout File

the layout file is here, main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
	android:orientation="vertical" android:layout_width="fill_parent"
	<TextView android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="Near Me" />
	<ListView android:id="@+id/list_nearme" android:divider="#FFCC00"
		android:dividerHeight="1dp" android:layout_width="fill_parent"

and the item.xml

<?xml version="1.0" encoding="utf-8"?>
  xmlns:android="" android:orientation="vertical"
  <TextView android:id="@+id/it_location_title" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:paddingLeft="10dp" android:paddingRight="10dp"
	<TextView android:id="@+id/it_location_description" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:paddingLeft="10dp" android:paddingRight="10dp"

the complete source code



25 thoughts on “Android Json Processing using GSON and Display in on a ListView

      • can you elaborate more? or perhaps show us the code? I have a hard time looking for a standard ways to do it, since everyone have their own way of integrating the OnItemClicklistener, it doesn’t fit into the tutorial you’ve provided up there.


      • have you implement onItemClickListener yet?
        after you implement it you must override the onItemClick method

        public void onItemClick(AdapterView parent, View view, int position,
        long id) {
        LocationEntity selectedLocation = locationArray.get(position);


        that simple, the key is to know the position param, since eclipse autocomplete doesn’t say which paramater show the selected position on the list.

    • Pertama-tama km harus dapetin Location untuk dibandingkannya nya dulu, disini saya tarus dalam variabel userLocation
      nanti cara hitung jaraknya seperti di bawah ini

      Float dist = userLocation.distanceTo(l) / 1000;
      try {
      distance = twoDForm.format(dist) + " Km";
      } catch (Exception e) {
      distance = "Not Available";

      • ohh gtu mas. makasih mas pencerahannya. oiy mas satu lagi. itu kan cma textview doank kan ya. klo misalny saya tambahin imageview di smping row textview ny, trs image ny itu nge parsing url image yg ad di jsonnya gmna ya? saya pake cara ini qo g keluar image nya ya ..
        ImageView imageView = (ImageView)convertView.findViewById(;
        Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(lm.imageUrl).getContent());
        }catch (MalformedURLException e) {
        }catch (IOException e) {

        kira2 ap yg harus di tambahin ya? mohon bantuanny mas, buat skripsi soalny.hehe.

  1. ohh gtu mas. makasih mas pencerahannya. oiy mas satu lagi. itu kan cma textview doank kan ya. klo misalny saya tambahin imageview di smping row textview ny, trs image ny itu nge parsing url image yg ad di jsonnya gmna ya? kira2 ap yg harus di tambahin ya? mohon bantuanny mas, buat skripsi soalny.hehe.

  2. Hey I wanted to give this a shot but it appears to be a little outdated. AsyncTask needs to be genericized, and it’s throwing an error. This can be fixed by changing the line:
    “private class LocationSync extends AsyncTask { …


    “private class LocationSync extends AsyncTask { …

    After that I’m still getting an error in the for loop, telling me there’s a “Type mismatch: cannot convert from element type Object to LocationModel”

    I’m pretty sure that’s being caused by the raw ArrayList. Any pointers?

    • maksudnya kalau item di tekan, untuk buka halaman lain yang isinya data dari item yang di klik, gampang sih, di listview nya di setOnItemClickListener, dan nantinya pada event OnItemClick passing intent ke activity lain.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s