从URL的Andr​​oid ocasionally下载图片 [英] Android ocasionally downloads images from url

查看:364
本文介绍了从URL的Andr​​oid ocasionally下载图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序的一部分是从URL下载图像,并分析他们ListView和单imgaview。 Generaly这是行不通的,但有些图像偶尔出现。

A part of my application is to download images from a url and parse them to listview and single imgaview. Generaly it does not work, however some images appear occasionally.

public class ImageLoader {

    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService; 

    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }

    int stub_id = R.drawable.ic_launcher;
    public void DisplayImage(String uurl, int loader, ImageView imageView)
    {
        String url = uurl.replaceAll(" ", "%20");
        url = url.replaceAll("\n", "%20");
        stub_id = loader;
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(loader);
        }
    }

    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
        return downloadBitmap(url);

        //from web
        /*try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }*/
    }
    Bitmap downloadBitmap(String url){
        Bitmap bmp = null;
        URL url_1 = null;
        try {
            url_1 = new URL(url);
             bmp = BitmapFactory.decodeStream(url_1.openConnection().getInputStream());
        } catch (Exception e) {
            Log.v("Error while downloading bitmap from url", e.getMessage());
        }
        return bmp;
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }

        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

filecash

filecash

public class FileCache {

    private File cacheDir;

    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"TempImages");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    public File getFile(String url){
        String filename=String.valueOf(url.hashCode());
        File f = new File(cacheDir, filename);
        return f;

    }

    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }

}

内存现金

public class MemoryCache {
    private Map<String, SoftReference<Bitmap>> cache=Collections.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());

    public Bitmap get(String id){
        if(!cache.containsKey(id))
            return null;
        SoftReference<Bitmap> ref=cache.get(id);
        return ref.get();
    }

    public void put(String id, Bitmap bitmap){
        cache.put(id, new SoftReference<Bitmap>(bitmap));
    }

    public void clear() {
        cache.clear();
    }
}

public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}

适配器

public class CandidateAdapter extends BaseAdapter{
    Context ctx;
    LayoutInflater lInflater;
    ArrayList<Candidate> objects;
    CandidateAdapter(Context context, ArrayList<Candidate> candidates) {
            ctx = context;
            objects = candidates;
            lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          }
    public int getCount() {
        return objects.size();
      }
    public Object getItem(int position) {
        return objects.get(position);
      }
    public long getItemId(int position) {
        return position;
      }
    Candidate getCandidate(int position) {
        return ((Candidate) getItem(position));
      }
    public View getView(int position, View convertView, ViewGroup parent) {
        // используем созданные, но не используемые view
        View view = convertView;
        if (view == null) {
          view = lInflater.inflate(R.layout.inbox_list_item, parent, false);
        }
        Candidate p = getCandidate(position);
        ((TextView) view.findViewById(R.id.from)).setText(p.get_name());
        ((TextView) view.findViewById(R.id.subject)).setText(p.get_office());
        ((RatingBar) view.findViewById(R.id.rateindicator)).setRating(p.get_ranking());
        int loader = R.drawable.loader;


        ImageView image = (ImageView) view.findViewById(R.id.photo);


        String image_url = p.get_photograph();


        ImageLoader imgLoader = new ImageLoader(ctx);


        imgLoader.DisplayImage(image_url, loader, image);
        return view;
    }



}

活动

public class InboxActivity extends ListActivity {

    List<Candidate> candidates;
    private DatabaseHandler db;

    public void onDestroy(){
        if (db != null)
            db.close();

        super.onDestroy();
        //db.close();
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inbox_list);
        db = new DatabaseHandler(this);
        candidates = db.getAllCandidates(1);
        db.close();
        CandidateAdapter adapter = new CandidateAdapter(this,(ArrayList) candidates);
        ListView lvMain = getListView();
        //String numofrows = "" + candidates.size();
        //Log.d("Number of candidates", numofrows);
        lvMain.setAdapter(adapter);
        lvMain.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.from)).getText().toString();
                Log.d("Name ", name);

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra("name", name);
                Log.d("Starting activity ", "Yeah ");
                startActivity(in);

            }
        });
    }





}

logcat的警告

logcat warnings

八月12日至16日:35:33.525:W /合子(33):preloaded绘制资源#0x1080093(RES /绘,华电国际/ sym_def_app_icon.png)与配置变化!

12-16 08:35:33.525: W/Zygote(33): Preloaded drawable resource #0x1080093 (res/drawable-hdpi/sym_def_app_icon.png) that varies with configuration!!

谁能帮我出图中的问题在这里?

Can anyone help me out figure the problem here?

推荐答案

我想可能是在URL问题意味着它包含在它的空白。所以下载图像如果URL包含下列code空白使用。

I think it might be problem in url means it contain blank space in it. so to download image if its url contain blank use below code.

public void DisplayImage(String uurl, int loader, ImageView imageView)
{
    String url = uurl.replaceAll(" ", "%20");
    stub_id = loader;
    imageViews.put(imageView, url);
    Bitmap bitmap=memoryCache.get(url);
    if(bitmap!=null)
        imageView.setImageBitmap(bitmap);
    else
    {
        queuePhoto(url, imageView);
        imageView.setImageResource(loader);
    }
}

使用这个从指定的URL下载的位图。

Use this to download bitmap from specified url.

Bitmap downloadBitmap(String url)
{
    URL url_1 = null;
    try {
        url_1 = new URL(url);
        bmp = BitmapFactory.decodeStream(url_1.openConnection().getInputStream());
    } catch (Exception e) {
        Log.v("Error while downloading bitmap from url", e.getMessage());
    }
    return bmp;
}

这篇关于从URL的Andr​​oid ocasionally下载图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆