Search code examples
androidandroid-intentevent-handlingimageviewbitmapfactory

Android Download Image through intentservice OK but can't set it in ImageVIew


I am struggling with my Android App code...

I am trying to download a picture (via an intentService) and then to display it by adding an ImageView to a LinearLayout.

So far so good, I have the absolutepath sent to my by the intentservice managing the download. I get the toast with the path name.

But I can't display the picture by adding an imageview... And I really don't know why...

At first, I thought my handler could not reach the layout but I managed to display a random image of my resources using setImageResource. So I guess the problem comes either from setimagebitmap or bitmapfactory decode...

In my Intentservice I have (output is the name of my File):

Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = output.getAbsolutePath();
try {
     messenger.send(msg);
} etc...

Back to my main activity, I have:

Private Handler handler = new Handler() {
    public void handleMessage(Message message) {

        // I Get the message
        Object path = message.obj;

        //Check if download went ok
        if (message.arg1 == RESULT_OK && path != null) {
        Toast.makeText(Update3sur3.this,
            "Downloaded" + path.toString(), Toast.LENGTH_LONG)
            .show();

            //Try to display the pic
            LinearLayout res2=(LinearLayout)findViewById(R.id.reslayout2);
        ImageView imgView2 = new ImageView(Update3sur3.this);
        Bitmap bitmap= BitmapFactory.decodeFile(path.toString());
        imgView2.setImageBitmap(bitmap);
        res2.addView(imgView2);
    } else {
        Toast.makeText(Update3sur3.this, "Download failed.",
            Toast.LENGTH_LONG).show();
      }
    };
  };

Thank you very much!

Laurent


Solution

  • At first I would try to make sure If I can access the file correctly i.e. follow these steps:

    1. use the decodeByteArray(byte[] data, int offset, int length) method instead of BitmapFactory.decodeFile(path.toString())

    2. To use this new method you will have to read the byte array of the file yourself, this will add extra steps, but you will be sure that you are reading the file correctly.

    3. Use FileInputStream to read bytes

    File imageFile = new File(path); byte imageData[] = new byte[(int)imageFile.length()];

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFile);

    in.read(imageData, 0, (int)imageFile.length());

    Log.d("", " Image File Size: " + imageFile.length()); //check here do you get the file size correctly?

    // Now imageData is the byte array that you will use to produce image so: decodeByteArray(imageData, 0, (int) imageFile.length());

    If the image still doesn't appear then put logging statements and print the size of the image and see if it is correct.