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
gilah keren banget.
hehehe, makasih makasih, ini juga ditulis atas saran pak sonny
Salam kenal. Wah, sudah mendalami Android nih. Saya baru sukses “Hello Android” :-)
Basic-nya Android itu Java?
kalau mau develop sih, bisa pakai bahasa macam-macam, tapi yang dari awal disupport langsung sama google ya Java
Salam kenal,
maw nanya ne, di List viewnya LatLang nya kok ga ke display ya??
kok cuma nama sama deskripsi?
iya di kode itu memang tidak saya tampilkan ke listview
btw caranya gmana yak?
Kan latlng tu typenya float ga kayak nama & deskripsi yg tipenya string,
pas saya pake ke setText -> holder.latlng.setText(lm.getLatlng())
kok errornya ga bisa soalnya float gt, ada masukan gak? :D
LatLng itu array of float, klo mau ditampilin pakai setText() ya diubah dulu jadi string
The source code of your example code does not exist.
ooops, my fault. now the link for the source code has been fixed.
thanks for the information
Thanks Bobby
Hello bob, km kembali lagi ke java akhirnya :D. wah jadi kepengin mendalami Android nie…
How to start a new activity each time i click on the list view?
Just implements an OnItemClicklistener, and override the OnItemClick method
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.
mas mw nanya donk. klo mw nampilin jaraknya di listviewny gmna ya?
terimakasih…
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.
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.
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?
ok thanks, now the code is updated
coba klw dgn screen shot hsil programnya kykny lbh mantap gan.hehe
seandainya, kalau tiap list view, di clik lagi keluar content lagi gimna? di layout yang beda, ? makasih
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.