Android ListView使用方法,处理Json数据

[转自]http://blog.csdn.net/woshisap/article/details/6621571

 1 package cn.capinfotech.json;
2
3 import java.net.URI;
4 import java.util.ArrayList;
5 import java.util.HashMap;
6 import java.util.List;
7
8 import org.apache.http.HttpEntity;
9 import org.apache.http.HttpResponse;
10 import org.apache.http.client.HttpClient;
11 import org.apache.http.client.methods.HttpPost;
12 import org.apache.http.impl.client.DefaultHttpClient;
13 import org.apache.http.util.EntityUtils;
14 import org.json.JSONArray;
15 import org.json.JSONObject;
16
17 import android.app.Activity;
18 import android.os.Bundle;
19 import android.util.Log;
20 import android.widget.ListView;
21 import android.widget.SimpleAdapter;
22 import android.widget.Toast;
23
24 public class MainActivity extends Activity {
25 private static final String TAG = "MainActivity";
26 private List<HashMap<String, Object>> videos = null;
27 private HashMap<String, Object> video = null;
28
29 private ListView listView = null;
30 private static String url = "http://10.0.2.2:8088/Struts2_sxt/getjson.action";
31
32 @Override
33 public void onCreate(Bundle savedInstanceState) {
34 super.onCreate(savedInstanceState);
35 setContentView(R.layout.main);
36
37 listView = (ListView)findViewById(R.id.videos);
38 getPDAServerData(url);
39
40 }
41
42 private void getPDAServerData(String url) {
43 HttpClient client = new DefaultHttpClient();
44 //提拱默认的HttpClient实现
45 HttpPost request;
46 try {
47 request = new HttpPost(new URI(url));
48 HttpResponse response = client.execute(request);
49 // 判断请求是否成功
50 if (response.getStatusLine().getStatusCode() == 200) { //200表示请求成功
51 HttpEntity entity = response.getEntity();
52 if (entity != null) {
53 String out = EntityUtils.toString(entity, "UTF-8");
54 Log.i(TAG, out);
55
56 JSONArray jsonArray = new JSONArray(out);
57
58 videos = new ArrayList<HashMap<String, Object>>();
59 for(int i = 0; i<jsonArray.length(); i++) {
60 JSONObject jsonObject = (JSONObject) jsonArray.get(i);
61 int id = jsonObject.getInt("id");
62 String name = jsonObject.getString("title");
63 int timelength = jsonObject.getInt("timelength");
64
65 video = new HashMap<String, Object>();
66 video.put("id", id);
67 video.put("name", name);
68 video.put("timelength", "时长为:" + timelength);
69
70 videos.add(video);
71 }
72
73 SimpleAdapter adapter = new SimpleAdapter(this, videos, R.layout.item,
74 new String[]{"name", "timelength"},
75 new int[]{R.id.title, R.id.timelength}
76 );
77 listView.setAdapter(adapter);
78
79 }
80 }
81 } catch(Exception e) {
82 e.printStackTrace();
83 Log.e(TAG, e.toString());
84 Toast.makeText(MainActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
85 }
86 }
87 }

需要注意的事,ListView需要一个显示Item的layout, 上面第73行的R.layout.item就是这个东西。第75行的R.id...也是这个layout里面的控件的id。

posted @ 2011-09-02 14:41  baby_cz  阅读(2509)  评论(0编辑  收藏  举报