listview加载网络图片

时间:2023-01-01 03:54:35

ListView加载网络数据和图片

2013-09-25 00:08:10|  分类: 默认分类 |  标签:android  |举报|字号 订阅

 
 
如,从服务器端获得商品名称、价格、简介和图片,加载到Android ListView中。又如加载微博内容。
 
需了解熟悉:
1、ListView行布局,排版,getView方法
这个案例可以说是实现ListView图文混排的网络版。关于在ListView中实现排版的方法,参      考:http://blog.163.com/ppy2790@126/blog/static/1032422412013731115643829/
2、异步任务的实现,Handler+Thread , AsyncTask
3、JSON解析方式
 
 
实现思路:
1、异步加载服务器访问商品数据(json格式)
      封装网络访问的方法
2、json数据转为Adapter数据(List<Map<String,Object>>)
     封装数据转换的方法
3、Adapter先加载文本内容信息
     使用AsyncTask加载网络访问的集合数据
     加载ListView中的文本信息
4、json数据中有图片信息(路径),异步读取加载图片
    采用接口回调的方法,加载图片信息(Handler+Thread)
listview加载网络图片
 

public class HttpUtil {

public static final String BASE_URL = "http://10.0.2.2:8080/jsontest/servlet/ProductServlet";

public static final String IMG_URL = "http://10.0.2.2:8080/jsontest/upload/";

public static HttpClient httpClient = new DefaultHttpClient();

// post方法访问服务器,返回json字符串

public static String getRequest(String url){

String result = null;

HttpGet httpGet = new HttpGet(url);

try {

HttpResponse httpResponse = httpClient.execute(httpGet);

if (httpResponse.getStatusLine().getStatusCode() == 200) {

result = EntityUtils.toString(httpResponse.getEntity(),"utf-8");

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return result;

}

// 字符串转成集合数据

public static void resultString2List(List<Map<String ,Object>> list, String str,String title) {

try {

JSONObject jsonObject = new JSONObject(str);

JSONArray jsonArray = jsonObject.getJSONArray(title);

for (int i = 0; i < jsonArray.length(); i++) {

JSONObject jsonObject2 = jsonArray.getJSONObject(i);

Map<String ,Object> map = new HashMap<String, Object>();

Iterator<String> iterator = jsonObject2.keys();

while (iterator.hasNext()) {

String key = iterator.next();

Object value = jsonObject2.get(key);

map.put(key, value);

}

list.add(map);

}

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

// post方法访问服务器,返回集合数据

public static List<Map<String,Object>> getRequest2List(String url,String title){

List<Map<String,Object>> list = new ArrayList<Map<String ,Object>>();

resultString2List(list, url, title);

return list;

}

// get方法访问服务器,返回json字符串

public static String postRequest(String url, Map<String,String> rawParams) throws Exception{

HttpPost post = new HttpPost(url);

List<NameValuePair> params = new ArrayList<NameValuePair>();

for (String key:rawParams.keySet()) {

params.add(new BasicNameValuePair(key, rawParams.get(key)));

}

post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

HttpResponse httpResponse = httpClient.execute(post);

if(httpResponse.getStatusLine().getStatusCode() == 200){

String result = EntityUtils.toString(httpResponse.getEntity());

return result;

}

return null;

}

//post访问的方法,还可继续封装,略。。。

}

异步任务,得到网络json转换的集合数据,并在完成后加载到listview中(onPostExcute方法中执行)

public class MyTask extends AsyncTask<String, Void, List<Map<String,Object>>>{

@Override

protected void onPreExecute() {

// TODO Auto-generated method stub

super.onPreExecute();

progressDialog.show();

}

@Override

protected void onPostExecute(List<Map<String, Object>> result) {

// TODO Auto-generated method stub

super.onPostExecute(result);

adapter.setData(result);

listview.setAdapter(adapter);

adapter.notifyDataSetChanged();

progressDialog.dismiss();

}

@Override

protected List<Map<String, Object>> doInBackground(String... params) {

// TODO Auto-generated method stub

List<Map<String,Object>> list ;

String str = HttpUtil.getRequest(params[0]);

list = HttpUtil.getRequest2List(str, "products");

return list;

}

}

 
OnCreate()方法中启动异步任务:

progressDialog = new ProgressDialog(this);

progressDialog.setTitle("正在下载....");

adapter = new MyAdapter(this);

new MyTask().execute(HttpUtil.BASE_URL);

 
Adapter:
 

public class MyAdapter extends BaseAdapter{

private Context context;

private LayoutInflater layoutInflater;

private List<Map<String,Object>> list;

public MyAdapter(Context context) {

this.context = context;

layoutInflater = layoutInflater.from(context);

}

public List getData(){

return list;

}

public void setData(List<Map<String,Object>> data){

this.list = data;

}

@Override

public int getCount() {

// TODO Auto-generated method stub

return list.size();

}

@Override

public Object getItem(int position) {

// TODO Auto-generated method stub

return list.get(position);

}

@Override

public long getItemId(int position) {

// TODO Auto-generated method stub

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

// TODO Auto-generated method stub

View view = null;

final ViewHolder viewHolder;

if (convertView == null ) {

convertView = layoutInflater.inflate(R.layout.item, null);

viewHolder = new ViewHolder();

viewHolder.id = (TextView)convertView.findViewById(R.id.textView1);

viewHolder.name = (TextView)convertView.findViewById(R.id.textView2);

viewHolder.address = (TextView)convertView.findViewById(R.id.textView3);

viewHolder.img = (ImageView)convertView.findViewById(R.id.imageView1);

convertView.setTag(viewHolder);

}else{

viewHolder = (ViewHolder)convertView.getTag();

}

viewHolder.id.setText(list.get(position).get("sid").toString());

viewHolder.name.setText(list.get(position).get("name").toString());

viewHolder.address.setText(list.get(position).get("addr").toString());

//接口回调的方法,完成图片的读取;

DownImage downImage = newDownImage(HttpUtil.IMG_URL+list.get(position).get("pic").toString()+".jpg");

downImage.loadImage(new ImageCallBack() {

@Override

public void getDrawable(Drawable drawable) {

// TODO Auto-generated method stub

viewHolder.img.setImageDrawable(drawable);

}

});

return convertView;

}

}

public class ViewHolder{

ImageView img;

TextView id;

TextView name;

TextView address;

}

 
 
异步加载图片的类:

public class DownImage {

public String image_path;

public DownImage(String image_path) {

this.image_path = image_path;

}

public void loadImage(final ImageCallBack callBack){

final Handler handler = new Handler(){

@Override

public void handleMessage(Message msg) {

// TODO Auto-generated method stub

super.handleMessage(msg);

Drawable drawable = (Drawable) msg.obj;

callBack.getDrawable(drawable);

}

};

new Thread(new Runnable() {

@Override

public void run() {

// TODO Auto-generated method stub

try {

Drawable drawable = Drawable.createFromStream(new URL(image_path).openStream(), "");

Message message = Message.obtain();

message.obj = drawable;

handler.sendMessage(message);

} catch (MalformedURLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}).start();

}

public interface ImageCallBack{

public void getDrawable(Drawable drawable);

}

}