当前位置:操作系统 > 安卓/Android >>

Android中ListView异步加载数据

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.openConnect

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,