首页 / ANDROID / android 数据异步加载
android 数据异步加载
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了android 数据异步加载,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6419字,纯文字阅读大概需要10分钟。
内容图文
public class MainActivity extends Activity { ListView listView; File cache; //访问其他线程在当前线程中存放的数据 Handler handler = new Handler(){ publicvoid handleMessage(Message msg) { listView.setAdapter(new ContactAdapter(MainActivity.this, (List<Contact>)msg.obj, R.layout.listview_item, cache)); } }; @Override publicvoid 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() { publicvoid run() { try { List<Contact> data = ContactService.getContacts(); handler.sendMessage(handler.obtainMessage(22, data)); } catch (Exception e) { e.printStackTrace(); } } }).start(); } @Override protectedvoid onDestroy() { for(File file : cache.listFiles()){ file.delete(); } cache.delete(); super.onDestroy(); } }
public class ContactAdapter extends BaseAdapter { private List<Contact> data; privateint 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); } /** * 得到数据的总数 */publicint getCount() { return data.size(); } /** * 根据数据索引得到集合所对应的数据 */public Object getItem(int position) { return data.get(position); } publiclong 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; } privatevoid asyncImageLoad(ImageView imageView, String path) { AsyncImageTask asyncImageTask = new AsyncImageTask(imageView); asyncImageTask.execute(path); } //实现资源的异步加载,可以防止打开很多条线程 影响程序的功能String输入参数类型,Uri子线程返回的数据类型privatefinalclass 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(); } returnnull; } protectedvoid onPostExecute(Uri result) {//运行在主线程,参数为doInBackground返回的值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(); } */privatefinalclass DataWrapper{ public ImageView imageView; public TextView textView; public DataWrapper(ImageView imageView, TextView textView) { this.imageView = imageView; this.textView = textView; } } }
public class ContactService { /** * 获取联系人 * @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()); } returnnull; } privatestatic 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)); }elseif("name".equals(pullParser.getName())){ contact.name = pullParser.nextText(); }elseif("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; } /** * 获取网络图片,如果图片存在于缓存中,就返回该图片,否则从网络中加载该图片并缓存起来 * @param path 图片路径 * @return*/publicstatic Uri getImage(String path, File cacheDir) throws Exception{// path -> MD5 ->32字符串.jpg File localFile = new File(cacheDir, MD5.getMD5(path)+ path.substring(path.lastIndexOf("."))); if(localFile.exists()){ return Uri.fromFile(localFile); }else{ HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode() == 200){ FileOutputStream outStream = new FileOutputStream(localFile); InputStream inputStream = conn.getInputStream(); byte[] buffer = newbyte[1024]; int len = 0; while( (len = inputStream.read(buffer)) != -1){ outStream.write(buffer, 0, len); } inputStream.close(); outStream.close(); return Uri.fromFile(localFile); } } returnnull; } }
public class MD5 { public static String getMD5(String content) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(content.getBytes()); return getHashString(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } returnnull; } privatestatic String getHashString(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for (byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } }
原文:http://www.cnblogs.com/heml/p/3521184.html
内容总结
以上是互联网集市为您收集整理的android 数据异步加载全部内容,希望文章能够帮你解决android 数据异步加载所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。