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 http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/

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 LocationModel.java 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) {
		this.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 LocationList.java 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;
    }
}

LocationAdapter.java 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
        if(convertView==null)
        {
            convertView = mInflater.inflate(R.layout.item, null);
			holder = new ViewHolder();
			holder.title = (TextView) convertView
					.findViewById(R.id.it_location_title);
			holder.description = (TextView) convertView
					.findViewById(R.id.it_location_description);

			convertView.setTag(holder);

        }
        else
        {
        	holder = (ViewHolder) convertView.getTag();
        }

        holder.title.setText(lm.getName());
		holder.description.setText(lm.getDescription());

		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 com.google.gson.Gson;

import android.app.Activity;
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) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        lv = (ListView) findViewById(R.id.list_nearme);

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

        lv.setTextFilterEnabled(true);
		lv.setAdapter(locationAdapter);

		try {
			new LocationSync().execute("http://vivid-snow-43.heroku.com/nearme.json");
		} 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 {
	    			    client.Execute(RequestMethod.GET);
	    			} catch (Exception e) {
	    			    e.printStackTrace();
	    			}

	    			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())
	        {
				locationArray.add(lm);
	        }
	        locationAdapter.notifyDataSetChanged();
	    }

	}
}

Layout File

the layout file is here, main.xml

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

and the item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView android:id="@+id/it_location_title" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:paddingLeft="10dp" android:paddingRight="10dp"
		android:textSize="20sp">
	</TextView>
	<TextView android:id="@+id/it_location_description" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:paddingLeft="10dp" android:paddingRight="10dp"
		android:textSize="14sp">
	</TextView>
</LinearLayout>

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.

        thanks

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


        @Override
        public void onItemClick(AdapterView parent, View view, int position,
        long id) {
        LocationEntity selectedLocation = locationArray.get(position);
        Toast.makeText(this,selectedLocation.getName(),Toast.LENGTH_LONG);

        }

        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 ..
        try{
        ImageView imageView = (ImageView)convertView.findViewById(R.id.image);
        Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(lm.imageUrl).getContent());
        imageView.setImageBitmap(bitmap);
        }catch (MalformedURLException e) {
        e.printStackTrace();
        }catch (IOException e) {
        e.printStackTrace();
        }

        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 { …

    to

    “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 comment