安卓笔记之BaseAdapter(解析JSON数据并通过BaseAdapter把数据显示至ListView)

package com.example.day0324_json;


import java.util.List;
import java.util.Map;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
private String url = "http://10.16.154.26:8080/ServerForJSON/JsonServlet";
private ListView listView;
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

MyTask myTask = new MyTask();
myTask.execute(url);

}

class MyTask extends AsyncTask<String, Void, List<Map<String, Object>>> {
private ProgressDialog dialog;

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("标题");
dialog.setMessage("正在下载");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();*/
}

@Override
protected List<Map<String, Object>> doInBackground(String... params) {
// 从URl读取字符串(该字符串是JSON格式的)
String jsonStr = HttpUtils.getJSONStr(params[0]);
//JSONUtils里面的parseJSONStr方法解析json数据
List<Map<String, Object>> person = JSONUtils.parseJSONStr(jsonStr);
/*    for (Map<String, Object> c : person) {
// Log.i("doInBackground", jsonStr);
Log.i("doInBackground", c + "");
}*/

return person;
}

@Override
protected void onPostExecute(final List<Map<String, Object>> result) {
// TODO Auto-generated method stub
//dialog.dismiss();
//Log.i("onPostExecute", result + "");
listView = (ListView) findViewById(R.id.lv);
listView.setAdapter(new BaseAdapter() {

@Override
public View getView(int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View view = null;
ViewHolder holder = null;
if (convertView == null) {
view = LayoutInflater.from(MainActivity.this).inflate(
R.layout.items, null);
holder = new ViewHolder();
holder.textView1 = (TextView) view.findViewById(R.id.tv1);
holder.textView2 = (TextView) view.findViewById(R.id.tv2);
holder.imageView = (ImageView) view.findViewById(R.id.iv);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder) view.getTag();
}

Map<String, Object> map = result.get(position);    
holder.imageView.setImageBitmap((Bitmap) map.get("bitmap"));
holder.textView1.setText(map.get("id")+"");
holder.textView2.setText(map.get("name") + "");

return view;

}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return result.size();
}

class ViewHolder {
public TextView textView1, textView2;
public ImageView imageView;

}

});
image = (ImageView) findViewById(R.id.imageview);
listView.setEmptyView(image);
super.onPostExecute(result);
}
}
}
package com.example.day0324_json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.graphics.Bitmap;

public class JSONUtils {
    //录入JSON字符串并返回List<Map<String,Object>>
    public static List<Map<String, Object>> parseJSONStr(String jsonStr){
        try {
            List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
            
            //JSON字符串中{}表示JSONObject
            //这里创建JSONObject对象
            JSONObject jsonObject = new JSONObject(jsonStr);
            //根据JSONObject对象中冒号前的值(key)获取冒号后的内容(vaule)
            //后面的值是JSONArray数组
            JSONArray jsonArray = (JSONArray) jsonObject.get("person");
            
            //遍历数组
            for (int i = 0; i < jsonArray.length(); i++) {
                Map<String,Object> map = new HashMap<String, Object>();
                JSONObject jsonObject2= (JSONObject) jsonArray.get(i);
                String address = jsonObject2.getString("address");
                int id = jsonObject2.getInt("id");
                String name = jsonObject2.getString("name");
                String url ="Http://10.16.154.26:8080/"+address; 
                //通过URL构造出一个BitMap位图对象
                Bitmap bitmap = HttpUtils.getHttpBitmap(url);
                //map.put("address", address);
                map.put("id", id);
                map.put("name", name);
                map.put("bitmap", bitmap);
                list.add(map);
                
                
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
package com.example.day0324_json;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Entity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class HttpUtils {
    //从网络url上下载字符串
    public static String getJSONStr(String url){
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        try {
            HttpResponse httpResponse = client.execute(get);
            if (httpResponse.getStatusLine().getStatusCode()==200) {
                HttpEntity entity = httpResponse.getEntity();
                InputStream is =  entity.getContent();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] bys = new byte[1024];
                int len = 0;
                while((len = is.read(bys))!=-1){
                    baos.write(bys, 0, len);
                }
                return baos.toString();
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        
        return null;
    }
    //输入网址返回一个位图对象
    public static Bitmap getHttpBitmap(String url){
        HttpClient client = new DefaultHttpClient();//HTTP客户端
        HttpGet get = new HttpGet(url);//GET请求
        try {
            HttpResponse httpResponse = client.execute(get);
            if (httpResponse.getStatusLine().getStatusCode()==200) {
                HttpEntity entity = httpResponse.getEntity();
                InputStream is = entity.getContent();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] bys = new byte[1024];
                int len  =0;
                while((len = is.read(bys))!=-1){
                    baos.write(bys, 0, len);
                }
                byte[] data = baos.toByteArray();
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                return bitmap;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        return null;
    }
}

 

posted @ 2016-03-25 19:37  丨缘来是你丨  阅读(1847)  评论(0编辑  收藏  举报