为了账号安全,请及时绑定邮箱和手机立即绑定

ListView获取网络图片并且缓存

标签:
Java
package com.example.xinwen;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class shipeiqi extends BaseAdapter {

    private List<NewsBean> mlist;
    private LayoutInflater mflater;
    private imageloader mImageloader;

    public shipeiqi(Context context , List<NewsBean> data){
        mlist = data;
        mflater = LayoutInflater.from(context);
        mImageloader=new imageloader();

    }

//  private void OnItemClick(AdapterView<?> pratnt, View view, 
//          int position, long id) {
//  
//      ////点击事件

    @Override
    public int getCount() {
        // TODO 自动生成的方法存根
        return mlist.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO 自动生成的方法存根
        return mlist.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO 自动生成的方法存根
        return 0;
    }

    @Override
    public View getView(int position, View con, ViewGroup arg2) {
        viewholder aa = null;
        if (con==null) {
            aa = new viewholder();
            con=mflater.inflate(R.layout.item, null);
            aa.tupian=(ImageView) con.findViewById(R.id.tupian);
            aa.neirong=(TextView) con.findViewById(R.id.wenben);
            aa.biaoti=(TextView) con.findViewById(R.id.biaoti);
            con.setTag(aa);
        }else{
            aa=(viewholder) con.getTag();

        }
        aa.tupian.setImageResource(R.drawable.ic_launcher);
        String url =mlist.get(position).newstupian;
        aa.tupian.setTag(url);//图片不符解决
        //new imageloader().showtupianthread(aa.tupian, mlist.get(position).newstupian);
        mImageloader.showImageByAsyncTask(aa.tupian, url);
        aa.biaoti.setText(mlist.get(position).newsbiaoti);
        aa.neirong.setText(mlist.get(position).newsneirong);

        return con;
    }

    class viewholder{
        public TextView biaoti,neirong;
        public  ImageView tupian;

    }

}

package com.example.xinwen;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.R.integer;
import android.R.string;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.LruCache;
import android.widget.ImageView;

public class imageloader {

private  ImageView mimageView;
private String murl;
private LruCache<String, Bitmap> mCache;

public imageloader(){
    int maxMemory = (int) Runtime.getRuntime().maxMemory();//获取最大可用内存
    int cacheSize = maxMemory/4;
    mCache = new LruCache<String, Bitmap>(cacheSize){

        @Override
        protected int sizeOf(String key, Bitmap value){

            //每次存入缓存的时候调用
            return value.getByteCount();
        }
    };
}

//增加到缓存
public void addBitmapToCache(String url,Bitmap bitmap){
    if (getBitmapfromCache(url)==null) {
        mCache.put(url, bitmap);
    }
}

//从缓冲中获取数据
    public Bitmap getBitmapfromCache(String url){

        return mCache.get(url);
    }

 public Handler  mhandler= new Handler(){

    public void handleMessage(Message msg) {

        super.handleMessage(msg);

        if(mimageView.getTag().equals(murl)){//图片刷新多次解决办法
            mimageView.setImageBitmap((Bitmap) msg.obj);//图片刷新多次解决办法
        }///图片刷新多次解决办法
        }
    };

public void showtupianthread(ImageView tupianImageView , final String url) {
        mimageView = tupianImageView;
        murl =url;  //图片刷新多次解决办法
        new Thread(){
         @Override
        public void run() {
             super.run();
            Bitmap  bitmap =  getBitmapURL(url);
             Message message = Message.obtain();   //obtain获得
             message.obj=bitmap;
             mhandler.sendMessage(message);
        }

     }.start();
     }  

public  Bitmap getBitmapURL(String urlString){
    Bitmap bitmap;        
    URL url;
    InputStream is = null;
    try {
        url = new URL(urlString);
        HttpURLConnection  connection = (HttpURLConnection) url.openConnection(); //固定格式
        is  =  new BufferedInputStream(connection.getInputStream()); 
        bitmap = BitmapFactory.decodeStream(is);   //bitmap Factory 制造   decodeStream破译流
        connection.disconnect();      //释放资源
        return bitmap;
    } catch (MalformedURLException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
    } catch (IOException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
    }finally{
        try {
            is.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

    return null;
}

public void showImageByAsyncTask(ImageView imageView,String url) {

       //从缓存中取出对应的图片
        Bitmap bitmap = getBitmapfromCache(url);
        //如果缓冲中没有 必须去下载
        if (bitmap==null) {
            new newsAsyncTask(imageView,url).execute(url);
        }else{
            imageView.setImageBitmap(bitmap);

    }
    }

class  newsAsyncTask extends AsyncTask<String, Void, Bitmap>{
    private ImageView mImageView;
    private String murl;

    public newsAsyncTask(ImageView imageView,String url){
        mimageView = imageView;
        murl=url;

    }

    @Override
    protected Bitmap doInBackground(String... params) {
        String url= params[0];
        //从网络上获取图片
        Bitmap bitmap  = getBitmapURL(url);
        //如果没有必须从网络上下载
        if (bitmap!=null) {
            //将不再缓存的图片加入缓存 
            addBitmapToCache(url, bitmap);
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        // TODO 自动生成的方法存根
        super.onPostExecute(bitmap);
        mimageView.setImageBitmap(bitmap);

    }
}

}


点击查看更多内容
3人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消