Android ListView异步加载数据
1.主Activity
public class MainActivity extends Activity {
private ListView listView;
private ArrayList<Person> persons;
private ListAdapter adapter;
private Handler handler=null;
//xml文件的网络地址
final String path="http://192.168.5.10:8080/FileServer/person.xml";
@SuppressLint("HandlerLeak")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView=(ListView) super.findViewById(R.id.listview);
//cache=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/cache");
//开一条子线程加载网络数据
Runnable runnable=new Runnable()
{
public void run()
{
try
{
Thread.sleep();
//xmlwebData解析网络中xml中的数据
persons=XmlwebData.getData(path);
//发送消息,并把persons结合对象传递过去
handler.sendMessage(handler.obtainMessage(, persons));
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
};
try
{
//开启线程
new Thread(runnable).start();
//handler与线程之间的通信及数据处理
handler=new Handler()
{
public void handleMessage(Message msg)
{
if(msg.what==)
{
//msg.obj是获取handler发送信息传来的数据
@SuppressWarnings("unchecked")
ArrayList<Person> person=(ArrayList<Person>) msg.obj;
//给ListView绑定数据
BinderListData(person);
}
}
};
}
catch (Exception e)
{
e.printStackTrace();
}
}
//绑定数据
public void BinderListData(ArrayList<Person> person)
{
//创建adapter对象
adapter=new ListViewAdapter(R.layout.item,this,person);
//将Adapter绑定到listview中
listView.setAdapter(adapter);
}
}
2.从网络中获取xml文件并解析数据
public class XmlwebData
{
private static ArrayList<Person> persons=null; public static ArrayList<Person> getData(final String path)
{
try
{
URL url=new URL(path);
Person person=null; HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout();
if(conn.getResponseCode()==)
{
InputStream inputstream=conn.getInputStream();
XmlPullParser xml=Xml.newPullParser();
xml.setInput(inputstream, "UTF-8");
int event=xml.getEventType(); while(event!=XmlPullParser.END_DOCUMENT)
{
switch (event)
{
//开始解析文档
case XmlPullParser.START_DOCUMENT:
persons=new ArrayList<Person>();
break;
case XmlPullParser.START_TAG: String value=xml.getName();
if(value.equals("person"))
{//person对象的初始化必须在这里初始化不然可能出现为null的现象
person=new Person();
//获取属性值
person.setId(new Integer(xml.getAttributeValue()));
}
else if(value.equals("name"))
{
person.setName(xml.nextText());
}
else if(value.equals("sex"))
{
person.setSex(xml.nextText());
}
else if(value.equals("age"))
{
person.setAge(new Integer(xml.nextText()));
}
else if(value.equals("path"))
{
person.setPath(xml.nextText());
}
break;
case XmlPullParser.END_TAG:
if(xml.getName().equals("person"))
{
persons.add(person);
System.out.println(person.getName());;
person=null;
}
break;
}
//解析下一个对象
event=xml.next();
}
return persons;
}
}
catch (Exception e)
{
e.printStackTrace();
} return null; } }
3.Person对象类
public class Person
{
private int id;
private String name;
private String sex;
private String path;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(){ }
}
4.Adapter数据适配器类
public class ListViewAdapter extends BaseAdapter implements ListAdapter
{ private ArrayList<Person> data;
private int id;
private Context context;
private LayoutInflater inflater;
public ListViewAdapter(int item, MainActivity mainActivity,ArrayList<Person> data)
{
this.data=data;
this.context=mainActivity;
this.id=item;
inflater=LayoutInflater.from(context);
} @Override
public int getCount()
{
return data.size();
} @Override
public Object getItem(int position)
{
return data.get(position);
} @Override
public long getItemId(int position)
{
return position;
} @Override
public View getView(int position, View view, ViewGroup arg2)
{
TextView name=null;
TextView sex=null;
TextView age=null;
ImageView img=null;
if(view==null)
{
view=inflater.inflate(id, null);
name=(TextView) view.findViewById(R.id.PersonName);
sex=(TextView) view.findViewById(R.id.PersonSex);
age=(TextView) view.findViewById(R.id.PersonAge);
img=(ImageView) view.findViewById(R.id.Personimage);
//保存view对象到ObjectClass类中
view.setTag(new ObjectClass(name,sex,age,img));
}
else
{
//得到保存的对象
ObjectClass objectclass=(ObjectClass) view.getTag();
name=objectclass.name;
sex=objectclass.sex;
age=objectclass.age;
img=objectclass.img;
} Person person=(Person) data.get(position);
//帮数据绑定到控件上
name.setText(person.getName().toString());
sex.setText("性别:"+person.getSex().toString());
age.setText("年龄:"+String.valueOf(person.getAge()));
//加载图片资源
LoadImage(img,person.getPath());
return view; } private void LoadImage(ImageView img, String path)
{
//异步加载图片资源
AsyncTaskImageLoad async=new AsyncTaskImageLoad(img);
//执行异步加载,并把图片的路径传送过去
async.execute(path); } private final class ObjectClass
{
TextView name=null;
TextView sex=null;
TextView age=null;
ImageView img=null;
public ObjectClass(TextView name, TextView sex, TextView age,ImageView img)
{
this.name=name;
this.sex=sex;
this.age=age;
this.img=img;
}
} }
5.异步加载图片类
public class AsyncTaskImageLoad extends AsyncTask<String, Integer, Bitmap> {
private ImageView Image=null;
public AsyncTaskImageLoad(ImageView img)
{
Image=img;
}
//运行在子线程中
protected Bitmap doInBackground(String... params) {
try
{
URL url=new URL(params[]);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout();
if(conn.getResponseCode()==)
{
InputStream input=conn.getInputStream();
Bitmap map=BitmapFactory.decodeStream(input);
return map;
}
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Bitmap result)
{
if(Image!=null && result!=null)
{
Image.setImageBitmap(result);
}
super.onPostExecute(result);
}
}
6.网络中的person.xml文件内容为
<?xml version="1.0" encoding="UTF-8"?>
<Persons>
<person id="">
<name>张三</name>
<sex>男</sex>
<age></age>
<path>http://192.168.5.10:8080/FileServer/chengjisihan.jpg</path>
</person>
<person id="">
<name>李斯</name>
<sex>男</sex>
<age></age>
<path>http://192.168.5.10:8080/FileServer/laozi.jpg</path>
</person>
<person id="">
<name>王五</name>
<sex>男</sex>
<age></age>
<path>http://192.168.5.10:8080/FileServer/lilongji.jpg</path>
</person>
<person id="">
<name>庞聪</name>
<sex>男</sex>
<age></age>
<path>http://192.168.5.10:8080/FileServer/lishimin.jpg</path>
</person>
<person id="">
<name>孙膑</name>
<sex>男</sex>
<age></age>
<path>http://192.168.5.10:8080/FileServer/lisi.jpg</path>
</person>
<person id="">
<name>孙武</name>
<sex>男</sex>
<age></age>
<path>http://192.168.5.10:8080/FileServer/liyuan.jpg</path>
</person> <person id="">
<name>成吉思汗</name>
<sex>男</sex>
<age></age>
<path>http://192.168.5.10:8080/FileServer/sunbiin.jpg</path>
</person> <person id="">
<name>李渊</name>
<sex>男</sex>
<age></age>
<path>http://192.168.5.10:8080/FileServer/sunwu.jpg</path>
</person> <person id="">
<name>李隆基</name>
<sex>男</sex>
<age></age>
<path>http://192.168.5.10:8080/FileServer/wangwu.jpg</path>
</person>
<person id="">
<name>武则天</name>
<sex>女</sex>
<age></age>
<path>http://192.168.5.10:8080/FileServer/wuzetian.jpg</path>
</person>
</Persons>
运行结果如下

Android ListView异步加载数据的更多相关文章
- android 网络异步加载数据进度条
ProgressDialog progressDialog = null; public static final int MESSAGETYPE = 0; private void execute( ...
- android listview 异步加载图片并防止错位
网上找了一张图, listview 异步加载图片之所以错位的根本原因是重用了 convertView 且有异步操作. 如果不重用 convertView 不会出现错位现象, 重用 convertVie ...
- 又优化了一下 Android ListView 异步加载图片
写这篇文章并不是教大家怎么样用listview异步加载图片,因为这样的文章在网上已经有很多了,比如这位仁兄写的就很好: http://www.iteye.com/topic/685986 我也是因为看 ...
- Android中ListView异步加载数据
1.主Activity public class MainActivity extends Activity { private ListView listView; private ArrayLis ...
- android ListView异步加载图片(双缓存)
首先声明,参考博客地址:http://www.iteye.com/topic/685986 对于ListView,相信很多人都很熟悉,因为确实太常见了,所以,做的用户体验更好,就成了我们的追求... ...
- android ListView 分页加载数据
1.mainActivity <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" ...
- 转:Android ListView 异步加载图片
http://www.iteye.com/topic/1118828 http://www.iteye.com/topic/1127914 这样做无疑是非常可取的方法,但是加载图片时仍然会感觉到轻微的 ...
- Android的ListView异步加载图片时,错位、重复、闪烁问题的分析及解决方法
Android ListView异步加载图片错位.重复.闪烁分析以及解决方案,具体问题分析以及解决方案请看下文. 我们在使用ListView异步加载图片的时候,在快速滑动或者网络不好的情况下,会出现图 ...
- listview异步加载图片并防止错位
android listview 异步加载图片并防止错位 网上找了一张图, listview 异步加载图片之所以错位的根本原因是重用了 convertView 且有异步操作. 如果不重用 conver ...
随机推荐
- ASP.NET CompareValidator 控件在VS2012中出错的问题
CompareValidator 控件用于将由用户输入到输入控件的值与输入到其他输入控件的值或常数值进行比较. -------如果输入控件为空,则不会调用任何验证函数,并且验证将成功.使用 Requi ...
- Ext.Net学习笔记07:Ext.Net DirectMethods用法详解
使用DirectMethods在JS中调用C#方法 我承认,这个标题有点噱头,其实应该是通过DirectMethods,在JS中通过异步调用的方式执行服务器端的方法. 来看一个例子吧: [Direct ...
- mysql:1153 Got a packet bigger than ‘max_allowed_packet’ bytes的解决方法
备份还原或数据导入报错1153:Got a packet bigger than'max_allowed_packet'bytes的问题 这个问题可以有2个解决方法: 1.临时修改: mysql> ...
- Codevs 1191 数轴染色
1191 数轴染色 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold 题目描述 Description 在一条数轴上有N个点,分别是1-N.一开始所有的点都被染成黑色. ...
- js data日期初始化的5种方法new Date()
var objDate=new Date([arguments list]); 参数形式有以下5种: 1)new Date("month dd,yyyy hh:mm:ss"); 2 ...
- HTML5的全局属性
contentEditable:是否允许用户编辑元素中的内容.contentEditable有两个值,一个True 一个False. 例子: <ul contentEditable=" ...
- poco异步等待ActiveResult
#include "Poco/ActiveMethod.h"#include "Poco/ActiveResult.h"#include <utility ...
- Git中的fetch和pull
http://blog.haohtml.com/archives/12674 Git中从远程的分支获取最新的版本到本地有这样2个命令: 1. git fetch:相当于是从远程获取最新版本到本地,不会 ...
- 【web安全】第一弹:利用xss注入获取cookie
首先一定要先来吐槽一下tipask系统.这是一枚开源的类似百度知道的系统,但是漏洞多多,最基本的XSS注入都无法防御. 言归正传: [准备1] cookie接收服务器. 平时喜欢用sae,所以在sae ...
- react + iscroll5
react + iscroll5 经过几天的反复折腾,总算做出一个体验还不错的列表页了,主要支持了下拉刷新,上拉加载两个功能. 一开始直接采用了react-iscroll插件,它是基于iscroll插 ...