简体   繁体   中英

Set image to downloaded bitmap in a separate class

I am trying to pass an imageview to a non activity class that will handle looking up the image from online and then subsequently set the image. My error that I am receiving is that when trying to set the image , the bitmap is read as null even though it has been received.

my constructor

ImageView iview_image;
public ImageLoader(String url, Context newContext, ItemsDto items, ImageView imageView)
{
    try
    {
        Log.e("IMGURL",url);
        str_img=url;
        context=newContext;
        this.context=newContext;
        itemsDto=items;
        iview_image=imageView;
        iview_image.findViewById(R.id.icon);
    }

my async task

protected Void doInBackground(Void... arg0) 
{
    try 
    {
        Log.e("Async Img Load", "Before the try");
        //Sets image status to help other classes know when image is ready

        //image lookups
        URL url = new URL(str_img);
        HttpGet httpRequest = null;
        httpRequest = new HttpGet(url.toURI());

        //http get 
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
        HttpEntity entity = response.getEntity();
        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
        InputStream input = b_entity.getContent();
        bm_productImage = BitmapFactory.decodeStream(input);

        setBm_productImage(bm_productImage);

        str_imgStatus="Image recieved";
    } 
    catch (Exception e) 
    {
        Log.e("IMG_ERROR",e.toString());
    }       
    try{iview_image.setImageBitmap(getBm_productImage());}
    catch(Exception e){ Log.e("more errors wheee", e.toString());}
    doPendingActivity();
    return null;
}

@Override
protected void onPostExecute(Void result) 
{
    // TODO Auto-generated method stub
    super.onPostExecute(result);

    try
    {

    }
    catch(Exception e)
    {
        Log.e("Post_ERROR", e.toString());
    }
}

I've been where you are, and I'll give you a recommendation. However, first, I'll answer your question. The way I downloaded a stream from a URL and saved it into a Bitmap was:

try {
     URL url_obj = new URL(url);
     Bitmap imageToReturn =  BitmapFactory.decodeStream(url_obj.openConnection().getInputStream());
     return imageToReturn; // or do whatever you want
 } catch (MalformedURLException e) {
     return null;
 } catch (SocketTimeoutException e) {
     return null;
 } catch (IOException e) {
     return null;
 }

However, this solution is far from ideal when dealing with a lot of images. Android does not handle Bitmap s in memory well, and after you allocate a lot of Bitmap s in memory, it's a matter of time before you get an OutOfMemoryError exception thrown in your face.

I'd recommend using an image downloading/caching library like Picasso ( http://square.github.io/picasso/ ). You can download the JAR file and include it in your project (it's really just that simple!). The default usage scenario is:

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

but that's not the only possibility. If you want to save the bitmap or do something else with it, you can do:

Picasso.with(context).load(url).into(new Target() {
     @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
         // do what you want to do with the bitmap
         // if it has already been downloaded, it will be loaded from
         // cache (memory or disk). The loaded bitmap is in the parameter
    }

    @Override
    public void onBitmapFailed(Drawable drawable) {
        // whatever you want to do if if could not load the image
    }

    @Override
    public void onPrepareLoad(Drawable drawable) {
        // do whatever you want to do right before your request is submitted
    }
});

Any of the methods can be empty if you want, use it as needed (all of the methods need to be there though, or the interface implementation will give you a compilation error).

I think you'll find this solution to be better and it will save you headaches in the future when you start to run out of memory. I hope it was useful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM