您的位置:首页 > 移动开发 > Android开发

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

2011-09-02 14:41 495 查看
[转自]http://blog.csdn.net/woshisap/article/details/6621571

package cn.capinfotech.json;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private List<HashMap<String, Object>> videos = null;
private HashMap<String, Object> video = null;

private ListView listView = null;
private static String url = "http://10.0.2.2:8088/Struts2_sxt/getjson.action";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

listView = (ListView)findViewById(R.id.videos);
getPDAServerData(url);

}

private void getPDAServerData(String url) {
HttpClient client = new DefaultHttpClient();
//提拱默认的HttpClient实现
HttpPost request;
try {
request = new HttpPost(new URI(url));
HttpResponse response = client.execute(request);
// 判断请求是否成功
if (response.getStatusLine().getStatusCode() == 200) { //200表示请求成功
HttpEntity entity = response.getEntity();
if (entity != null) {
String out = EntityUtils.toString(entity, "UTF-8");
Log.i(TAG, out);

JSONArray jsonArray = new JSONArray(out);

videos = new ArrayList<HashMap<String, Object>>();
for(int i = 0; i<jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
String name = jsonObject.getString("title");
int timelength = jsonObject.getInt("timelength");

video = new HashMap<String, Object>();
video.put("id", id);
video.put("name", name);
video.put("timelength", "时长为:" + timelength);

videos.add(video);
}

SimpleAdapter adapter = new SimpleAdapter(this, videos, R.layout.item,
new String[]{"name", "timelength"},
new int[]{R.id.title, R.id.timelength}
);
listView.setAdapter(adapter);

}
}
} catch(Exception e) {
e.printStackTrace();
Log.e(TAG, e.toString());
Toast.makeText(MainActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
}
}
}


需要注意的事,ListView需要一个显示Item的layout, 上面第73行的R.layout.item就是这个东西。第75行的R.id...也是这个layout里面的控件的id。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐