Today we get on with ourÂseriesthat will connect our Android applications to internet webservices!

Next up in line:from JSON to a Listview. A lot of this project is identical to theprevious postin this series so try to look there first if you have any problems. On the bottom of the post ill add the Eclipse project with the source.

For this example i made use of an already existing JSON webservice locatedhere.

This is a piece of the JSON array that gets returned:

01 {"earthquakes": [
02 {
03 "eqid": "c0001xgp",
04 "magnitude": 8.8,
05 "lng": 142.369,
06 "src": "us",
07 "datetime": "2011-03-11 04:46:23",
08 "depth": 24.4,
09 "lat": 38.322
10 },
11 {
12 "eqid": "2007hear",
13 "magnitude": 8.4,
14 "lng": 101.3815,
15 "src": "us",
16 "datetime": "2007-09-12 09:10:26",
17 "depth": 30,
18 "lat": -4.5172
19 }
20 <--more -->
21
22 ]}

So how do we get this data into our application! Behold our getJSON class!

getJSON(String url)

01 publicstaticJSONObject getJSONfromURL(String url){
02
03 //initialize
04 InputStream is =null;
05 String result ="";
06 JSONObject jArray =null;
07
08 //http post
09 try{
10 HttpClient httpclient =newDefaultHttpClient();
11 HttpPost httppost =newHttpPost(url);
12 HttpResponse response = httpclient.execute(httppost);
13 HttpEntity entity = response.getEntity();
14 is = entity.getContent();
15
16 }catch(Exception e){
17 Log.e("log_tag","Error in http connection "+e.toString());
18 }
19
20 //convert response to string
21 try{
22 BufferedReader reader =newBufferedReader(newInputStreamReader(is,"iso-8859-1"),8);
23 StringBuilder sb =newStringBuilder();
24 String line =null;
25 while((line = reader.readLine()) !=null) {
26 sb.append(line +"\n");
27 }
28 is.close();
29 result=sb.toString();
30 }catch(Exception e){
31 Log.e("log_tag","Error converting result "+e.toString());
32 }
33
34 //try parse the string to a JSON object
35 try{
36 jArray =newJSONObject(result);
37 }catch(JSONException e){
38 Log.e("log_tag","Error parsing data "+e.toString());
39 }
40
41 returnjArray;
42 }

The code above can be divided in 3 parts.

  1. the first part makes the HTTP call
  2. the second part converts the stream into a String
  3. the third part converts the string to a JSONObject

Now we only have to implement this into out ListView. We can use the same method as in the XML tutorial. We make a HashMap that stores our data and we put JSON values in the HashMap. After that we will bind that HashMap to a SimpleAdapter. Here is how its done:

Implementation

01 ArrayList<HashMap<String, String>> mylist =newArrayList<HashMap<String, String>>();
02
03 //Get the data (see above)
04 JSONObject json =
05 JSONfunctions.getJSONfromURL("http://api.geonames.org/postalCodeSearchJSON?formatted=true&postalcode=9791&maxRows=10&username=demo&style=full");
06
07 try{
08 //Get the element that holds the earthquakes ( JSONArray )
09 JSONArray earthquakes = json.getJSONArray("earthquakes");
10
11 //Loop the Array
12 for(inti=0;i < earthquakes.length();i++){
13
14 HashMap<String, String> map =newHashMap<String, String>();
15 JSONObject e = earthquakes.getJSONObject(i);
16
17 map.put("id", String.valueOf(i));
18 map.put("name","Earthquake name:"+ e.getString("eqid"));
19 map.put("magnitude","Magnitude: "+ e.getString("magnitude"));
20 mylist.add(map);
21 }
22 }catch(JSONException e) {
23 Log.e("log_tag","Error parsing data "+e.toString());
24 }

After this we only need to make up the Simple Adapter

view source print
01 ListAdapter adapter =newSimpleAdapter(this, mylist , R.layout.main,
02 newString[] {"name","magnitude"},
03 newint[] { R.id.item_title, R.id.item_subtitle });
04
05 setListAdapter(adapter);
06
07 finalListView lv = getListView();
08 lv.setTextFilterEnabled(true);
09 lv.setOnItemClickListener(newOnItemClickListener() {
10 publicvoidonItemClick(AdapterView<?> parent, View view,intposition,longid) {
11 @SuppressWarnings("unchecked")
12 HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
13 Toast.makeText(Main.this,"ID '"+ o.get("id") +"' was clicked.", Toast.LENGTH_SHORT).show();
14

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. android客户端控制树莓派GPIO点亮LED灯
  2. Android(安卓)4.4 (KitKat) SMS Apis Cha
  3. android实现向右滑动返回功能
  4. Android的init过程(二):初始化语言(init.rc)解
  5. 深入剖析Android消息机制
  6. Android(安卓)应用程序消息处理机制(Loope
  7. Android中数据存储——SQLite数据库存储
  8. Qt for Android获取手机序列号/手机型号/
  9. Android引路蜂地图开发示例:基本知识
  10. 浅析Android线程模型