项目的总结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;
		}
	}
}

 

 

 

你可能感兴趣的:(异步加载)