`
zhengjj_2009
  • 浏览: 150007 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

项目的总结4、异步加载列表数据

 
阅读更多

异步加载数据的基本功能

将某台主机上的数据文件(文件加图片)读取到手机应用上,加以列表展示。

基本步骤:

1、新建一个工程,在manifest.xml添加访问权限、定义main.xml和item.xml的描述文件、定义信息实体bean。

 

2、实现ContactService的业务逻辑:

      getContacts():访问服务器上的数据文件(xml),并进行解析;

      getImage():获取服务器上的图片资源,并缓存在本地的SD卡上

 

3、在MainActivity中获取数据内容,并实现ListView数据的绑定

 

4、实现ContactAdapter的所有方法,并在处理获取图片时采用AsyncTask进行处理

 

===============================================================

1、新建一个工程,在manifest.xml添加访问权限、定义main.xml和item.xml的描述文件、定义信息实体bean。

 

<uses-permission android:name="android.permission.INTERNET"/><!-- 访问internet权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><!-- 往SDCard写入数据权限 -->

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listView"/>

</LinearLayout>

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
    <ImageView android:layout_width="match_parent" android:layout_height="400dp" android:id="@+id/imageView" />

    <TextView android:layout_width="match_parent" android:layout_height="wrap_content"
        android:textSize="18sp" android:textColor="#FF0000" android:id="@+id/textView"  />
</LinearLayout>

 

2、实现ContactService的业务逻辑:

getContacts():访问服务器上的数据文件(xml),并进行解析;

getImage():获取服务器上的图片资源,并缓存在本地的SD卡上

 

/**
	 * 获取联系人
	 * @return
	 */
	public static List<Contact> getContacts() throws Exception{
		String path = "http://192.168.1.100:8080/web/list.xml";
		HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if(conn.getResponseCode() == 200){
			return parseXML(conn.getInputStream());
		}
		return null;
	}

	private static List<Contact> parseXML(InputStream xml) throws Exception{
		List<Contact> contacts = new ArrayList<Contact>();
		Contact contact = null;
		XmlPullParser pullParser = Xml.newPullParser();
		pullParser.setInput(xml, "UTF-8");
		int event = pullParser.getEventType();
		while(event != XmlPullParser.END_DOCUMENT){
			switch (event) {
			case XmlPullParser.START_TAG:
				if("contact".equals(pullParser.getName())){
					contact = new Contact();
					contact.id = new Integer(pullParser.getAttributeValue(0));
				}else if("name".equals(pullParser.getName())){
					contact.name = pullParser.nextText();
				}else if("image".equals(pullParser.getName())){
					contact.image = pullParser.getAttributeValue(0);
				}
				break;

			case XmlPullParser.END_TAG:
				if("contact".equals(pullParser.getName())){
					contacts.add(contact);
					contact = null;
				}
				break;
			}
			event = pullParser.next();
		}
		return contacts;
	}

 

3、在MainActivity中获取数据内容,并实现ListView数据的绑定

 

public class MainActivity extends Activity {
	ListView listView;
	File cache;
	
	Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			 listView.setAdapter(new ContactAdapter(MainActivity.this, (List<Contact>)msg.obj, 
					 R.layout.listview_item, cache));
		}		
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listView = (ListView) this.findViewById(R.id.listView);
        
        cache = new File(Environment.getExternalStorageDirectory(), "cache");
        if(!cache.exists()) cache.mkdirs();
        
        new Thread(new Runnable() {			
			public void run() {
				try {
					List<Contact> data = ContactService.getContacts();
					handler.sendMessage(handler.obtainMessage(22, data));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();       
    }

	@Override
	protected void onDestroy() {
		for(File file : cache.listFiles()){
			file.delete();
		}
		cache.delete();
		super.onDestroy();
	}
    
}

 

 

4、实现ContactAdapter的所有方法,并在处理获取图片时采用AsyncTask进行处理

 

public class ContactAdapter extends BaseAdapter {
	private List<Contact> data;
	private int listviewItem;
	private File cache;
	LayoutInflater layoutInflater;
	
	public ContactAdapter(Context context, List<Contact> data, int listviewItem, File cache) {
		this.data = data;
		this.listviewItem = listviewItem;
		this.cache = cache;
		layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	/**
	 * 得到数据的总数
	 */
	public int getCount() {
		return data.size();
	}
	/**
	 * 根据数据索引得到集合所对应的数据
	 */
	public Object getItem(int position) {
		return data.get(position);
	}
	
	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView imageView = null;
		TextView textView = null;
		
		if(convertView == null){
			convertView = layoutInflater.inflate(listviewItem, null);
			imageView = (ImageView) convertView.findViewById(R.id.imageView);
			textView = (TextView) convertView.findViewById(R.id.textView);
			convertView.setTag(new DataWrapper(imageView, textView));
		}else{
			DataWrapper dataWrapper = (DataWrapper) convertView.getTag();
			imageView = dataWrapper.imageView;
			textView = dataWrapper.textView;	
		}
		Contact contact = data.get(position);
		textView.setText(contact.name);
		asyncImageLoad(imageView, contact.image);
		return convertView;
	}
    private void asyncImageLoad(ImageView imageView, String path) {
    	AsyncImageTask asyncImageTask = new AsyncImageTask(imageView);
    	asyncImageTask.execute(path);
		
	}
    
    private final class AsyncImageTask extends AsyncTask<String, Integer, Uri>{
    	private ImageView imageView;
		public AsyncImageTask(ImageView imageView) {
			this.imageView = imageView;
		}
		protected Uri doInBackground(String... params) {//子线程中执行的
			try {
				return ContactService.getImage(params[0], cache);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		protected void onPostExecute(Uri result) {//运行在主线程
			if(result!=null && imageView!= null)
				imageView.setImageURI(result);
		}	
    }
	/*
	private void asyncImageLoad(final ImageView imageView, final String path) {
		final Handler handler = new Handler(){
			public void handleMessage(Message msg) {//运行在主线程中
				Uri uri = (Uri)msg.obj;
				if(uri!=null && imageView!= null)
					imageView.setImageURI(uri);
			}
		};
		
		Runnable runnable = new Runnable() {			
			public void run() {
				try {
					Uri uri = ContactService.getImage(path, cache);
					handler.sendMessage(handler.obtainMessage(10, uri));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		new Thread(runnable).start();
	}
*/
	private final class DataWrapper{
		public ImageView imageView;
		public TextView textView;
		public DataWrapper(ImageView imageView, TextView textView) {
			this.imageView = imageView;
			this.textView = textView;
		}
	}
}

 

 

 

分享到:
评论

相关推荐

    vue项目小结 - 滚动监听钩子、时间求解、加载、路由、pinia、异步请求、界面展示、数据架构技巧等核心功能总结

    vue项目小结 - 滚动监听钩子、时间求解、加载、路由、pinia、异步请求、界面展示、数据架构技巧等核心功能总结

    2018年最新vue2.5 硅谷外卖视频

    24_Vue项目_异步显示食品分类轮播列表.avi 25_Vue项目_使用watch和$nextTick解决轮播的bug.avi 26_Vue项目_异步显示商家列表.avi 27_Vue项目_使用svg显示加载中提示界面.avi 28_Vue项目_Star组件.avi 29_Vue...

    2018年最新vue2.5 硅谷外卖视频+源码

    配置代理实现跨域ajax请求.avi 21_Vue项目_创建vuex的整体结构.avi 22_Vue项目_使用vuex管理首页数据.avi 23_Vue项目_异步显示当前地地址.avi 24_Vue项目_异步显示食品分类轮播列表.avi 25_Vue项目_使用watch和$...

    Android新闻客户端

    具有HttpPost获取网络数据、使用JSON解析、Fragment页面、AsyncTask异步加载图片、Handler、Listview展示界面,上拉获取更多数据等功能。该案例是一个综合性较为全面的应用,通过该案例的学习可以对基础只是做一个...

    ASP.NET4高级程序设计第4版 带目录PDF 分卷压缩包 part1

    另外,还专门介绍了ASP.NET4 新增的功能,如MVC 和动态数据等。  《ASP.NET 4高级程序设计(第4版)》适合各层次的ASP.NET程序员阅读。 =================== 第一部分 核心概念 第1章 ASP.NET简介 1.1 ASP.NET的...

    【尚硅谷】徐靖博 最新电商项目实战(完结)

    o* g3 S 30.03 sku功能跳转 31.04 客户端js函数中的el表达式 32.05 异步加载spu列表数据# M& R, \7 \3 y z- w+ a% }( g" ^ 33.06 用复选框操作属性列表显示 D+ k( T; J. J" `2 u 34.07 属性参数的提交) O0 o, s0 X ...

    ASP.NET4高级程序设计(第4版) 3/3

    另外,还专门介绍了ASP.NET4 新增的功能,如MVC 和动态数据等。  《ASP.NET 4高级程序设计(第4版)》适合各层次的ASP.NET程序员阅读。 作者简介 作者:(美)麦克唐纳 目录 第一部分 核心概念 第1章 ASP.NET简介 ...

    python入门到高级全栈工程师培训 第3期 附课件代码

    01 数据类型和变量总结 02 集合定义和基本操作方法 03 集合关系运算交,差,并集 04 集合的其他内置方法 05 集合补充 06 百分号字符串拼接 07 format字符串格式化 08 数学意义的函数与python中的函数 09 为何要有...

    互联网创意产品众筹平台

    │ 13-zTree树形结构-Demo4-一次加载数据,避免多次数据库交互,提高效率7 M) d& `5 L5 T2 d7 R$ s │ 14-zTree树形结构-Demo5-一次加载数据,Map集合解决双层for性能问题 │ 0 D% f8 ?. j2 W( U' z, e ├─众筹项目-第...

    浅谈jQuery绑定事件会叠加的解决方法和心得总结

    关于jQuery的学习中我忽略了一个取消绑定事件.unbind()的...起初我写的是静态页面html,行选功能完全没有问题,后来换成jsp页面,ajax动态加载数据进来后,问题就来了,由于ajax异步请求,两边表格发送请求加载数据有先

    2.ASP.NET.2.0.高级编程(第4版) [1/7]

    12.2.1 从各种数据源中批量加载数据 372 12.2.2 批处理多个更新 381 12.2.3 多个活动的结果集(MARS) 388 12.2.4 命令的异步执行 394 12.2.5 异步连接 415 12.3 小结 416 第13章 使用XML 417 13.1 XML基础 417...

    ASP.NET2.0高级编程(第4版)1/6

    26.8 异步使用Web服务973 26.9 小结976 第27章 配置977 27.1 配置概述977 27.1.1 服务器配置文件978 27.1.2 应用程序配置文件979 27.1.3 配置的应用979 27.1.4 检测配置文件的变化980 27.1.5 配置文件的格式980 ...

    Spring.3.x企业应用开发实战(完整版).part2

    第13章 任务调度和异步执行器 13.1 任务调度概述 13.2 Quartz快速进阶 13.2.1 Quartz基础结构 13.2.2 使用SimpleTrigger 13.2.3 使用CronTrigger 13.2.4 使用Calendar 13.2.5 任务调度信息存储 13.3 在Spring中使用...

    Spring3.x企业应用开发实战(完整版) part1

    第13章 任务调度和异步执行器 13.1 任务调度概述 13.2 Quartz快速进阶 13.2.1 Quartz基础结构 13.2.2 使用SimpleTrigger 13.2.3 使用CronTrigger 13.2.4 使用Calendar 13.2.5 任务调度信息存储 13.3 在Spring中使用...

    asp.net知识库

    也论该不该在项目中使用存储过程代替SQL语句 如何使数据库中的表更有弹性,更易于扩展 存储过程——天使还是魔鬼 如何获取MSSQLServer,Oracel,Access中的数据字典信息 C#中利用GetOleDbSchemaTable获取数据库内表信息...

    精通Windows.API-函数、接口、编程实例.pdf

    3.5.3 生成项目 64 3.5.4 调试 65 3.5.5 选项与设置 65 3.6 开发环境配置总结 66 第4章 文件系统 67 4.1 概述 67 4.1.1 文件系统的基本概念 67 4.1.2 文件系统主要API 68 4.2 磁盘和驱动器管理 70...

    GoodProject Maven Webapp.zip

    通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。 传统的网页(不使用 AJAX)如果需要更新内容,必须重载整个网页页面。 系统...

Global site tag (gtag.js) - Google Analytics