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

Android中ListView异步加载数据

2013-07-21 11:49 375 查看
1.主Activity

1 public class MainActivity extends Activity {
2
3     private ListView listView;
4     private ArrayList<Person> persons;
5     private ListAdapter adapter;
6     private Handler handler=null;
7     //xml文件的网络地址
8     final String path="http://192.168.5.10:8080/FileServer/person.xml";
9     @SuppressLint("HandlerLeak")
10     protected void onCreate(Bundle savedInstanceState) {
11         super.onCreate(savedInstanceState);
12         setContentView(R.layout.main);
13
14         listView=(ListView) super.findViewById(R.id.listview);
15         //cache=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/cache");
16
17         //开一条子线程加载网络数据
18         Runnable runnable=new Runnable()
19         {
20             public void run()
21             {
22                 try
23                 {
24                     Thread.sleep(2000);
25                     //xmlwebData解析网络中xml中的数据
26                     persons=XmlwebData.getData(path);
27                     //发送消息,并把persons结合对象传递过去
28                     handler.sendMessage(handler.obtainMessage(0, persons));
29                 }
30                 catch (InterruptedException e)
31                 {
32                     e.printStackTrace();
33                 }
34             }
35         };
36
37         try
38         {
39             //开启线程
40             new Thread(runnable).start();
41             //handler与线程之间的通信及数据处理
42             handler=new Handler()
43             {
44                 public void handleMessage(Message msg)
45                 {
46                     if(msg.what==0)
47                     {
48                         //msg.obj是获取handler发送信息传来的数据
49                         @SuppressWarnings("unchecked")
50                         ArrayList<Person> person=(ArrayList<Person>) msg.obj;
51                         //给ListView绑定数据
52                         BinderListData(person);
53                     }
54                 }
55             };
56         }
57         catch (Exception e)
58         {
59             e.printStackTrace();
60         }
61     }
62
63     //绑定数据
64     public void BinderListData(ArrayList<Person> person)
65     {
66         //创建adapter对象
67         adapter=new ListViewAdapter(R.layout.item,this,person);
68         //将Adapter绑定到listview中
69         listView.setAdapter(adapter);
70     }
71
72 }


2.从网络中获取xml文件并解析数据

1 public class XmlwebData
2 {
4     private static ArrayList<Person> persons=null; 6     public static ArrayList<Person> getData(final String path)
7     {
8                 try
9                 {
10                     URL url=new URL(path);
11                     Person person=null;

13                     HttpURLConnection conn=(HttpURLConnection) url.openConnection();
14                     conn.setRequestMethod("GET");
15                     conn.setConnectTimeout(5000);
16                     if(conn.getResponseCode()==200)
17                     {
18                         InputStream inputstream=conn.getInputStream();
21                         XmlPullParser xml=Xml.newPullParser();
22                         xml.setInput(inputstream, "UTF-8");
23                         int event=xml.getEventType();
24
25                         while(event!=XmlPullParser.END_DOCUMENT)
26                         {
27                             switch (event)
28                             {
29                             //开始解析文档
30                             case XmlPullParser.START_DOCUMENT:
31                                 persons=new ArrayList<Person>();
32                                 break;
33                             case XmlPullParser.START_TAG:
34
35                                 String value=xml.getName();
36                                 if(value.equals("person"))
37                                 {//person对象的初始化必须在这里初始化不然可能出现为null的现象
38                                     person=new Person();
39                                     //获取属性值
40                                     person.setId(new Integer(xml.getAttributeValue(0)));
41                                 }
42                                 else if(value.equals("name"))
43                                 {
44                                     person.setName(xml.nextText());
45                                 }
46                                 else if(value.equals("sex"))
47                                 {
48                                     person.setSex(xml.nextText());
49                                 }
50                                 else if(value.equals("age"))
51                                 {
52                                     person.setAge(new Integer(xml.nextText()));
53                                 }
54                                 else if(value.equals("path"))
55                                 {
56                                     person.setPath(xml.nextText());
57                                 }
58                                 break;
59                             case XmlPullParser.END_TAG:
60                                 if(xml.getName().equals("person"))
61                                 {
62                                     persons.add(person);
63                                     System.out.println(person.getName());;
64                                     person=null;
65                                 }
66                                 break;
67                             }
68                             //解析下一个对象
69                             event=xml.next();
70                         }
71                         return persons;
72                     }
73                 }
74                 catch (Exception e)
75                 {
76                     e.printStackTrace();
77                 }
78
79
80         return null;
81
82     }
83
84 }


3.Person对象类

1 public class Person
2 {
3     private int id;
4     private String name;
5     private String sex;
6     private String path;
7     public String getPath() {
8         return path;
9     }
10     public void setPath(String path) {
11         this.path = path;
12     }
13     private int age;
14     public int getId() {
15         return id;
16     }
17     public void setId(int id) {
18         this.id = id;
19     }
20     public String getName() {
21         return name;
22     }
23     public void setName(String name) {
24         this.name = name;
25     }
26     public String getSex() {
27         return sex;
28     }
29     public void setSex(String sex) {
30         this.sex = sex;
31     }
32     public int getAge() {
33         return age;
34     }
35     public void setAge(int age) {
36         this.age = age;
37     }
38     public Person(){
39
40     }
41 }


4.Adapter数据适配器类

1 public class ListViewAdapter extends BaseAdapter implements ListAdapter
2 {
3
4     private ArrayList<Person> data;
5     private int id;
6     private Context context;
7     private LayoutInflater inflater;
8     public ListViewAdapter(int item, MainActivity mainActivity,ArrayList<Person> data)
9     {
10         this.data=data;
11         this.context=mainActivity;
12         this.id=item;
13         inflater=LayoutInflater.from(context);
14     }
15
16     @Override
17     public int getCount()
18     {
19         return data.size();
20     }
21
22     @Override
23     public Object getItem(int position)
24     {
25         return data.get(position);
26     }
27
28     @Override
29     public long getItemId(int position)
30     {
31         return position;
32     }
33
34     @Override
35     public View getView(int position, View view, ViewGroup arg2)
36     {
37         TextView name=null;
38         TextView sex=null;
39         TextView age=null;
40         ImageView img=null;
41         if(view==null)
42         {
43             view=inflater.inflate(id, null);
44             name=(TextView) view.findViewById(R.id.PersonName);
45             sex=(TextView) view.findViewById(R.id.PersonSex);
46             age=(TextView) view.findViewById(R.id.PersonAge);
47             img=(ImageView) view.findViewById(R.id.Personimage);
48             //保存view对象到ObjectClass类中
49             view.setTag(new ObjectClass(name,sex,age,img));
50         }
51         else
52         {
53             //得到保存的对象
54             ObjectClass objectclass=(ObjectClass) view.getTag();
55             name=objectclass.name;
56             sex=objectclass.sex;
57             age=objectclass.age;
58             img=objectclass.img;
59         }
60
61         Person person=(Person) data.get(position);
62         //帮数据绑定到控件上
63         name.setText(person.getName().toString());
64         sex.setText("性别:"+person.getSex().toString());
65         age.setText("年龄:"+String.valueOf(person.getAge()));
66         //加载图片资源
67         LoadImage(img,person.getPath());
68         return view;
69
70     }
71
72     private void LoadImage(ImageView img, String path)
73     {
74         //异步加载图片资源
75         AsyncTaskImageLoad async=new AsyncTaskImageLoad(img);
76         //执行异步加载,并把图片的路径传送过去
77         async.execute(path);
78
79     }
80
81     private final class ObjectClass
82     {
83         TextView name=null;
84         TextView sex=null;
85         TextView age=null;
86         ImageView img=null;
87         public ObjectClass(TextView name, TextView sex, TextView age,ImageView img)
88         {
89             this.name=name;
90             this.sex=sex;
91             this.age=age;
92             this.img=img;
93         }
94     }
95
97 }


5.异步加载图片类

1 public class AsyncTaskImageLoad extends AsyncTask<String, Integer, Bitmap> {
2
3     private ImageView Image=null;
4
5     public AsyncTaskImageLoad(ImageView img)
6     {
7         Image=img;
8     }
9     //运行在子线程中
10     protected Bitmap doInBackground(String... params) {
11         try
12         {
13             URL url=new URL(params[0]);
14             HttpURLConnection conn=(HttpURLConnection) url.openConnection();
15             conn.setRequestMethod("POST");
16             conn.setConnectTimeout(5000);
17             if(conn.getResponseCode()==200)
18             {
19                 InputStream input=conn.getInputStream();
20                 Bitmap map=BitmapFactory.decodeStream(input);
21                 return map;
22             }
23         } catch (Exception e)
24         {
25             e.printStackTrace();
26         }
27         return null;
28     }
29
30     protected void onPostExecute(Bitmap result)
31     {
32         if(Image!=null && result!=null)
33         {
34             Image.setImageBitmap(result);
35         }
36
37         super.onPostExecute(result);
38     }
39 }


6.网络中的person.xml文件内容为

1 <?xml version="1.0" encoding="UTF-8"?>
2 <Persons>
3     <person id="1">
4         <name>张三</name>
5         <sex>男</sex>
6         <age>25</age>
7         <path>http://192.168.5.10:8080/FileServer/chengjisihan.jpg</path>
8     </person>
9     <person id="2">
10         <name>李斯</name>
11         <sex>男</sex>
12         <age>78</age>
13         <path>http://192.168.5.10:8080/FileServer/laozi.jpg</path>
14     </person>
15     <person id="3">
16         <name>王五</name>
17         <sex>男</sex>
18         <age>22</age>
19         <path>http://192.168.5.10:8080/FileServer/lilongji.jpg</path>
20     </person>
21     <person id="4">
22         <name>庞聪</name>
23         <sex>男</sex>
24         <age>31</age>
25         <path>http://192.168.5.10:8080/FileServer/lishimin.jpg</path>
26     </person>
27     <person id="5">
28         <name>孙膑</name>
29         <sex>男</sex>
30         <age>48</age>
31         <path>http://192.168.5.10:8080/FileServer/lisi.jpg</path>
32     </person>
33     <person id="6">
34         <name>孙武</name>
35         <sex>男</sex>
36         <age>58</age>
37         <path>http://192.168.5.10:8080/FileServer/liyuan.jpg</path>
38     </person>
39
40     <person id="7">
41         <name>成吉思汗</name>
42         <sex>男</sex>
43         <age>40</age>
44         <path>http://192.168.5.10:8080/FileServer/sunbiin.jpg</path>
45     </person>
46
47     <person id="8">
48         <name>李渊</name>
49         <sex>男</sex>
50         <age>36</age>
51         <path>http://192.168.5.10:8080/FileServer/sunwu.jpg</path>
52     </person>
53
54     <person id="9">
55         <name>李隆基</name>
56         <sex>男</sex>
57         <age>32</age>
58         <path>http://192.168.5.10:8080/FileServer/wangwu.jpg</path>
59     </person>
60     <person id="10">
61         <name>武则天</name>
62         <sex>女</sex>
63         <age>55</age>
64         <path>http://192.168.5.10:8080/FileServer/wuzetian.jpg</path>
65     </person>
66 </Persons>


运行结果如下



 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: