android开发中解决ListView异步加载图片错乱问题

 更新时间:2016年9月20日 20:01  点击:1312
发一个异步图片加载控件。网上也有大把的异步网络加载图片的控件,但是有一个问题,异步加载会造成列表中的图片混乱,因为列表的每一项的View都可能被重用,异步加载的时候多个异步线程引用到了同一个View将造成图片加载错乱。该控件解决这个问题
 代码如下 复制代码

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 异步图片控件
 * 使用:new AsyncImageView().asyncLoadBitmapFromUrl("http://xxxx","缓存路径"){
 *
 * @author gaoomei@gmail.com
 * @site http://obatu.sinaapp.com
 * @version 1.0
 * @2011-12-3
 */
public class AsyncImageView extends ImageView {

 /**
  * 异步task加载器
  */
 private AsyncLoadImage mAsyncLoad;

 /**
  * 下载回来的图片缓存存活时间,单位:秒(s),默认30分钟
  */
 private long mCacheLiveTime = 1800;

 public AsyncImageView(Context context) {
  super(context);
 }

 public AsyncImageView(Context context, AttributeSet attrs) {
  super(context, attrs);
 }

 public AsyncImageView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
 }

 /**
  *
  */
 @Override
 public void setImageDrawable(Drawable drawable) {
  if (mAsyncLoad != null) {
   mAsyncLoad.cancel(true);
   mAsyncLoad = null;
  }
  super.setImageDrawable(drawable);
 }

 /**
  * 重写下面几个设置图片资源的方法,目地是取消网络加载
  */
 @Override
 public void setImageResource(int resId) {
  cancelLoad();
  super.setImageResource(resId);
 }

 @Override
 public void setImageURI(Uri uri) {
  cancelLoad();
  super.setImageURI(uri);
 }

 @Override
 public void setImageBitmap(Bitmap bitmap) {
  cancelLoad();
  super.setImageBitmap(bitmap);
 }

 /**
  * 取消正在进行的异步task
  */
 public void cancelLoad() {
  if (mAsyncLoad != null) {
   mAsyncLoad.cancel(true);
   mAsyncLoad = null;
  }
 }

 /**
  * 设置图片存活时间
  *
  * @param second
  *            存活时间,单位【秒】,如果等于0或null,则不缓存
  */
 public void setCacheLiveTime(long second) {
  if (second == 0) {
   this.mCacheLiveTime = 0;
  } else if (second >= 0) {
   this.mCacheLiveTime = second * 1000;
  }
 }

 /**
  * 从网络异步加载
  *
  * @param url
  * @param saveFileName
  */
 public void asyncLoadBitmapFromUrl(String url, String saveFileName) {
  if (mAsyncLoad != null) {
   mAsyncLoad.cancel(true);
  }
  // AsyncTask不可重用,所以每次重新实例
  mAsyncLoad = new AsyncLoadImage();
  mAsyncLoad.execute(url, saveFileName);
 }

 /**
  * 异步加载器
  */
 private class AsyncLoadImage extends AsyncTask {
  /**
   * 是否取消
   */
  private boolean isCancel = false;

  @Override
  protected Bitmap doInBackground(String... params) {
   if (isCancel) {
    return null;
   }
   String url = params[0];
   String fileName = params[1];
   try {
    return getBitmap(url, fileName);
   } catch (IOException e) {
    e.printStackTrace();
   }
   return null;
  }

  @Override
  protected void onCancelled() {
   System.out.println("async load imgae cancel");
   isCancel = true;
  }

  @Override
  protected void onPostExecute(Bitmap result) {
   if (!isCancel && result != null) {
    AsyncImageView.this.setImageBitmap(result);
   }
  }
 }

 /**
  * 下载图片
  *
  * @param urlString
  *            url下载地址
  * @param fileName
  *            缓存文件路径
  * @throws IOException
  */
 private Bitmap getBitmap(String urlString, String fileName)
   throws IOException {
  if (fileName == null || fileName.trim().isEmpty()) {
   InputStream input = getBitmapInputStreamFromUrl(urlString);
   return BitmapFactory.decodeStream(input);
  }

  File file = new File(fileName);
  if (!file.isFile()
    || (mCacheLiveTime > 0 && (System.currentTimeMillis()
      - file.lastModified() > mCacheLiveTime))) {
   InputStream input = getBitmapInputStreamFromUrl(urlString);
   file = saveImage(input, fileName);
   // 如果文件结构创建失败,则直接从输入流解码图片
   if (file == null || !file.exists() || !file.canWrite()
     || !file.canRead()) {
    return BitmapFactory.decodeStream(input);
   }
  }
  return BitmapFactory.decodeFile(file.getAbsolutePath());
 }

 /**
  * 下载图片,输入InputStream
  *
  * @param urlString
  * @return
  * @throws IOException
  */
 private InputStream getBitmapInputStreamFromUrl(String urlString)
   throws IOException {
  URL url = new URL(urlString);
  URLConnection connection = url.openConnection();
  connection.setConnectTimeout(25000);
  connection.setReadTimeout(90000);
  return connection.getInputStream();
 }

 /**
  * 从输入流保存图片到文件系统
  *
  * @param fileName
  * @param input
  * @return
  */
 private File saveImage(InputStream input, String fileName) {
  if (fileName.trim().isEmpty() || input == null) {
   return null;
  }
  File file = new File(fileName);
  OutputStream output = null;
  try {
   file.getParentFile().mkdirs();
   if (file.exists() && file.isFile()) {
    file.delete();
   }
   if (!file.createNewFile()) {
    return null;
   }
   output = new FileOutputStream(file);
   byte[] buffer = new byte[4 * 1024];
   do {
    // 循环读取
    int numread = input.read(buffer);
    if (numread == -1) {
     break;
    }
    output.write(buffer, 0, numread);
   } while (true);
   output.flush();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    output.close();
   } catch (IOException e) {
    e.printStackTrace();
   } catch (Exception e2) {
    e2.printStackTrace();
   }
  }
  return file;
 }
}

本文章介绍了一个关于android通过http来实现文件上传功能,在服务器端我们是用php来实现的,有需要的朋友可以参考一下
 代码如下 复制代码

 

<?php

///如果有上传文件则接收

if($_FILES){  

$target_path = $target_path . basename( $_FILES['file1']['name']);

 try{ if(move_uploaded_file($_FILES['file1']['tmp_name'], $target_path)) { 

echo "The file ".  basename( $_FILES['file1']['name']).  " has been uploaded"; 

}

} catch( Exception $e ) { 

echo $e->getMessage();   } 

}

?>

Android 代码:

package com.nbcio.baishicha.test;
import java.io.DataOutputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.widget.Toast; 


public class test extends Activity {

/*

* 变量声明 newName:上传后在服务器上的文件名称

*

* uploadFile:要上传的文件路径 actionUrl:服务器对应的程序路径

*/

private String newName = "";

private String uploadFile = "";

private String actionUrl = "http://www.111cn.net/index.php";//这里定义你的上传路径 


@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
Intent intent = this.getIntent();

Bundle bundle = intent.getExtras();

newName = bundle.getString("fileName");

uploadFile = newName;
try {

String ok = post(actionUrl, newName);

Toast.makeText(this, "OK!", Toast.LENGTH_LONG).show();

finish(); 


} catch (IOException e) {

//

// TODO Auto-generated catch block

e.printStackTrace();

}



/* 上传文件到Server的方法 */

/**

*

* @param actionUrl

* @param params

* @param files

* @return

* @throws IOException

*/

public static String post(String actionUrl, String FileName)

throws IOException { 


String BOUNDARY = java.util.UUID.randomUUID().toString();

String PREFIX = "--", LINEND = "rn";

String MULTIPART_FROM_DATA = "multipart/form-data";

String CHARSET = "UTF-8";

 


URL uri = new URL(actionUrl);

HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

conn.setReadTimeout(5 * 1000);

// 缓存的最长时间

conn.setDoInput(true);// 允许输入

conn.setDoOutput(true);// 允许输出

conn.setUseCaches(false); // 不允许使用缓存

conn.setRequestMethod("POST");

conn.setRequestProperty("connection", "keep-alive");

conn.setRequestProperty("Charsert", "UTF-8");

conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA

+ ";boundary=" + BOUNDARY);

 


DataOutputStream outStream = new DataOutputStream(

conn.getOutputStream());

 


// 发送文件数据

if (FileName != "") {

 


StringBuilder sb1 = new StringBuilder();

sb1.append(PREFIX);

sb1.append(BOUNDARY);

sb1.append(LINEND);

sb1.append("Content-Disposition: form-data; name="file1"; filename=""

+ FileName + """ + LINEND);

sb1.append("Content-Type: application/octet-stream; charset="

+ CHARSET + LINEND);

sb1.append(LINEND);

outStream.write(sb1.toString().getBytes());

 


InputStream is = new FileInputStream(FileName);

byte[] buffer = new byte[1024];

int len = 0;

while ((len = is.read(buffer)) != -1) {

outStream.write(buffer, 0, len);

}

 
is.close();

outStream.write(LINEND.getBytes());

 
}

 
// 请求结束标志

byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();

outStream.write(end_data);

outStream.flush();

 
// 得到响应码

int res = conn.getResponseCode();

InputStream in = null;

if (res == 200) {

in = conn.getInputStream();

int ch;

StringBuilder sb2 = new StringBuilder();

while ((ch = in.read()) != -1) {

sb2.append((char) ch);

}

}

return in == null ? null : in.toString();

}

}

本文章分享一篇关于android与Web服务器交互时的cookie使用实例有需要的同学可以参考一下。

下面是具体的代码
/**

* 向网站发送get请求,url需按照api要求写,返回取得的信息。

* //这个专门给大众点评传入cookie参数用,目的是为了获得用户选择的城市信息

* @param url

* @param client

* @return String

* @author lvqiyong

*/

 代码如下 复制代码

public static String getRequest1(String url, DefaultHttpClient client,

String charset) throws Exception {

String result = null;

int statusCode = 0;

HttpGet getMethod = new HttpGet(url);

Log.d(TAG, "do the getRequest,url=" + url + "");

try {

getMethod.setHeader("User-Agent", USER_AGENT);

getMethod.setHeader("Cookie", "cy=" + value);//这个专门给大众点评传入cookie参数用,目的是为了获得用户选择的城市信息

// 添加用户密码验证信息

// client.getCredentialsProvider().setCredentials(

// new AuthScope(null, -1),

// new UsernamePasswordCredentials(mUsername, mPassword));

 

HttpResponse httpResponse = client.execute(getMethod);

// statusCode == 200 正常

statusCode = httpResponse.getStatusLine().getStatusCode();

Log.d(TAG, "statuscode = " + statusCode);

// 处理返回的httpResponse信息

if (statusCode == 200) {

result = retrieveInputStream(httpResponse.getEntity(), charset);

Cookie cookie;

String cookname,cookvalue;

List<Cookie> cookies = client.getCookieStore().getCookies();

if (cookies.isEmpty()) {

Log.i(TAG, "-------Cookie NONE---------");

} else {

for (int i = 0; i < cookies.size(); i++) {

// 保存cookie

cookie = cookies.get(i);

cookname = cookie.getName().trim();

cookvalue = cookie.getValue().trim();

if(cookname.equals("cy")){

name = cookname;

value = cookvalue;

}

}

}

} else

result = "networkerror";

} catch (ConnectTimeoutException e) {// 超时或网络连接出错

result = "timeouterror";

// e.printStackTrace();

} catch (ClientProtocolException e) {

result = "networkerror";

// e.printStackTrace();

} catch (Exception e) {

result = "readerror";

Log.e(TAG, e.getMessage());

throw new Exception(e);

} finally {

getMethod.abort();

}

return result;

}

本文章分享一个简单的android开发实现,功能是仿sina微博的listview更多分页按钮,有需要的朋友可以安看看。

因为百事查需要,需要制作这样的更多分页按钮,因为感觉新浪微博的更多分页按钮比较好,就尝试做了一下。
1、首先需要考虑布局,就是footer的布局,如下:

 代码如下 复制代码

<?xml version="1.0" encoding="UTF-8"?>

<LinearLayout android:layout_width="fill_parent" android:orientation="vertical"

android:layout_height="wrap_content" android:focusable="true"

xmlns:android="http://schemas.android.com/apk/res/android"

android:background="@drawable/loadmore" android:layout_centerVertical="true"

android:layout_centerHorizontal="true">

<!--

<Button android:id="@+id/loadMoreButton"

android:layout_width="fill_parent"

android:layout_height="wrap_content" android:text="更多" />

-->

<LinearLayout android:gravity="center" android:layout_height="wrap_content"

android:orientation="vertical" android:layout_width="fill_parent">

<ImageView android:background="@drawable/divider"

android:layout_height="2.0dip" android:layout_width="fill_parent" />

</LinearLayout>

<LinearLayout android:gravity="center" android:layout_gravity="center"

android:orientation="horizontal" android:layout_centerVertical="true"

android:layout_width="fill_parent" android:layout_height="60dip">

<TextView android:textSize="20.0sp" android:textColor="#ff545454"

android:gravity="center" android:id="@id/tv_msg" android:text="更多"

android:layout_width="fill_parent" android:layout_height="wrap_content"/>

<LinearLayout android:gravity="center" android:layout_height="wrap_content"

android:layout_gravity="center" android:orientation="horizontal"

android:id="@+id/llloading" android:layout_width="fill_parent">

<ProgressBar android:layout_gravity="center_vertical"

android:id="@id/footprogress" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:indeterminateBehavior="repeat"

style="?android:progressBarStyleSmallInverse" />

<TextView android:textColor="#ff000000" android:gravity="left|center"

android:padding="2.0px" android:layout_width="wrap_content"

android:layout_height="wrap_content" android:text="读取中" />

</LinearLayout>

</LinearLayout>

</LinearLayout>
期中上面的一个@drawable/loadmore是一个选择器如下

<?xml version="1.0" encoding="utf-8"?>

<selector

xmlns:android="http://schemas.android.com/apk/res/android"

>

<item

android:state_pressed="false"

android:drawable="@drawable/listview_gradient"

>

</item>

<item

android:state_pressed="true"

android:drawable="@drawable/list_selector_background_pressed"

>

</item>

</selector>其中list_selector_background_pressed系统带的一个按钮在listview源代码中可以找到或sdk中也有

2、同时加载footer布局

list_footer = (LinearLayout)LayoutInflater.from(FansActivity.this).inflate(R.layout.sinalist_footer, null);

tv_msg = (TextView)list_footer.findViewById(R.id.tv_msg);

loading = (LinearLayout)list_footer.findViewById(R.id.llloading);

//btloadmore = (Button)list_footer.findViewById(R.id.loadMoreButton);

listView = getListView();

top_panel = (View)findViewById(R.id.fans_top);

top_btn_left = (Button)top_panel.findViewById(R.id.top_btn_left);

top_btn_right = (Button)top_panel.findViewById(R.id.top_btn_right);

top_title = (TextView)top_panel.findViewById(R.id.top_title);

listView.addFooterView(list_footer, null, false);//利用FooterVIew分页动态加载,参数false是不让选择
3、list_footer中增加按钮事件如下

list_footer.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

try {

// Toast.makeText(FansActivity.this, "我将消失了",

// Toast.LENGTH_SHORT).show();

//list_footer.setBackgroundColor(Color.YELLOW);

//list_footer.invalidate();

new FansThread().start();

//tv_msg.setEnabled(false);

tv_msg.setVisibility(View.GONE);// 隐藏更多提示的TextView

loading.setVisibility(View.VISIBLE);// 显示最下方的进度条

} catch (Exception e) {

e.printStackTrace();

}

}

});

效果如下

[!--infotagslink--]

相关文章

  • AngularJS 实现按需异步加载实例代码

    AngularJS 通过路由支持多视图应用, 可以根据路由动态加载所需的视图, 在 AngularJS 的文档中有详细的介绍, 网上也有不少教程, 就不用介绍了!随着视图的不断增加,js文件会越来越多,而 AngularJS 默认需要把全部的js都一次性...2015-10-21
  • C#实现带进度条的ListView

    这篇文章主要介绍了C#实现带进度条的ListView 的相关资料,需要的朋友可以参考下...2020-06-25
  • C#获取鼠标在listview右键点击单元格的内容方法

    下面小编就为大家带来一篇C#获取鼠标在listview右键点击单元格的内容方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • 原生js页面滚动延迟加载图片

    这篇文章主要介绍了原生js页面滚动延迟加载图片的相关资料,现在瀑布流效果大行其道,各种网站都有应用,尤其是专业的图片类型的网站,感兴趣的朋友可以参考下...2015-12-21
  • C#实现读取DataSet数据并显示在ListView控件中的方法

    这篇文章主要介绍了C#实现读取DataSet数据并显示在ListView控件中的方法,涉及C#操作DataSet及ListView控件的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • C#中WPF ListView绑定数据的实例详解

    这篇文章主要介绍了C#中WPF ListView绑定数据的实例详解的相关资料,希望通过本文能帮助到大家,让大家理解掌握这部分内容,需要的朋友可以参考下...2020-06-25
  • Android ViewPager加载图片效果

    android项目中经常需要用到ViewPager加载图片,那么如何解决呢?本文介绍了Android ViewPager加载图片效果的教程,有需要的同学请参见下文。 目前项目中需要用到ViewPa...2017-01-22
  • C# WPF ListView控件的实例详解

    这篇文章主要介绍了C# WPF ListView控件的实例详解的相关资料,希望通过本能帮助到大家,让大家掌握这部分内容,需要的朋友可以参考下...2020-06-25
  • C#中将ListView中数据导出到Excel的实例方法

    首先 你需要添加引用Microsoft Excel 11.0 Object Library...2020-06-25
  • C# listview添加combobox到单元格的实现代码

    从别处转来的,自己进行了一些小的修改,还不错,你自己先拖一个ListView1和一个ComboBox1,需要的朋友可以参考下...2020-06-25
  • 详解vue-router的Import异步加载模块问题的解决方案

    这篇文章主要介绍了详解vue-router的Import异步加载模块问题的解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-05-14
  • 安卓开发使用定制的ArrayAdapter制作ListView的Items

    下面我们来看一篇关于使用定制的ArrayAdapter制作ListView的Items的例子,希望这个例子能够给各位同学带来帮助的哦。 背景介绍   对于现实世界中的商业移动应用...2016-09-20
  • ListView移动到指定位置的例子

    下面我们来看一篇关于ListView移动到指定位置的例子吧,希望文章能够给各位朋友带来帮助,具体的如下介绍. 关于ListView移动到指定位置有两种方法 listview.setSel...2016-11-01
  • C# ListView双击Item事件

    ListView没有Item的双击事件,只能通过变通的方法得到,以下是我的变通方法...2020-06-25
  • 关于ListView下隐藏控件的解决方案分享

    想实现一个功能,这个功能挺简单,就是当不是管理员用户登入的时候,那这个 删除 按钮就被隐藏掉;当是管理员用户的时候,就重新显示出来...2021-09-22
  • ASP.NET笔记之 ListView 与 DropDownList的使用

    本篇文章小编为大家介绍,ASP.NET笔记之 ListView 与 DropDownList的使用。需要的朋友参考下...2021-09-22
  • 点评js异步加载的4种方式

    这篇文章主要介绍了点评js异步加载的4种方式,帮助大家更全面的了解js异步加载方式,感兴趣的小伙伴们可以参考一下...2015-12-24
  • C# ListView 点击表头对数据进行排序功能的实现代码

    这篇文章主要介绍了C# ListView 点击表头对数据进行排序功能的实现代码,需要的朋友可以参考下...2020-06-25
  • jQuery滚动加载图片实现原理

    这篇文章主要介绍了jQuery滚动加载图片实现原理,通过四个方面来说明懒加载技术的原理,感兴趣的小伙伴们可以参考一下...2015-12-16
  • 利用JS实现简单的瀑布流加载图片效果

    今天学习了一个瀑布流加载效果,很多网站都有瀑布流效果,下面通过本文给大家分享利用JS实现简单的瀑布流加载图片效果,需要的朋友参考下吧...2017-04-27