Downloading image from server to android device

  • Replies:11
  • OpenNot stickiedAnswered
  • Forum posts: 21

Nov 16, 2014 12:34:28 PM via Website

Hi everyone, I'm trying to create an application that on one of its activities it downloads images from a remote server to the user's device. These are the functions I use:

private void getPicture() {
    Bitmap bitmap = DownloadImage("http://ibuy.pixub.com/ibuy/files/Pic5.jpg");

    ImageView img = (ImageView) findViewById(R.id.imageView);

    img.setImageBitmap(bitmap);
}

private Bitmap DownloadImage(String URL) {
    Bitmap bitmap = null;
    InputStream in;
    try {
        in = OpenHttpConnection(URL);
        bitmap = BitmapFactory.decodeStream(in);
        in.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return bitmap;
}

private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream in = null;

    int response;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK)
            in = httpConn.getInputStream();

    } catch (Exception ex) {
        throw new IOException("Error connecting");
    }
    return in;
}

My application falls on this line: throw new IOException("Error connecting");.
The path to the image is fine and I can see the image if I type it in the browser. Do I need to use a PHP file? Do I need just to change something in my code? Thank you in advance!

  • Forum posts: 118

Nov 17, 2014 9:59:32 AM via Website

It actually makes no sense to throw another exception when there is one already.

You can replace this line:

throw new IOException("Error connecting");

With:

ex.printStrackTrace();

If it still doesn't work, I wish to see the error in your logcat in a reply :)

  • Forum posts: 21

Nov 17, 2014 10:17:55 AM via Website

I changed the exception and now it says the exception was caused by a NullPointerException in the "in.close();" row. It means that the OpenHttpConnection function returns null. Do you have any suggestions for me?

  • Forum posts: 118

Nov 17, 2014 10:47:57 AM via Website

Itzick Binder

I changed the exception and now it says the exception was caused by a NullPointerException in the "in.close();" row. It means that the OpenHttpConnection function returns null. Do you have any suggestions for me?

I certainly do :)

Replace the following:

if (response == HttpURLConnection.HTTP_OK)
            in = httpConn.getInputStream();

With:

if (response == 200)
            in = httpConn.getInputStream();
else
            Log.w("getResponseCode", String.valueOf(response));

If you've done that, run your app and keep a close eye on your logcat. If you're using Android Studio, a blue line should pop up with the name "getResponseCode" along with a number. Make a screenshot of the line or copy and paste it in a reply to see if the HTTP connection could reach the image on your website. If a blue line doesn't pop up, it means that it should most likely work. A valid connection means response code 200 if I'm not mistaken.

  • Forum posts: 21

Nov 17, 2014 11:17:36 AM via Website

I did what you told me and now I get these error messages:
User uploaded photo
The blue line of error is the row where "httpConn.connect();" is written, so it probably could not even connect to the server. :(

  • Forum posts: 118

Nov 17, 2014 12:06:44 PM via Website

Oh yeah, of course. You're trying to make a connection on your main thread which is your UI thread.

Replace the following:

private void getPicture() {

    Bitmap bitmap = DownloadImage("http://ibuy.pixub.com/ibuy/files/Pic5.jpg");

    ImageView img = (ImageView) findViewById(R.id.imageView);

    img.setImageBitmap(bitmap);
}

With:

private void getPicture() {
    new DownloadImageTask().execute();
}

class DownloadImageTask extends AsyncTask<Void, Integer, Long> { 
    Bitmap bitmap = null;
    protected Long doInBackground(Void... urls) {
        bitmap = DownloadImage("http://ibuy.pixub.com/ibuy/files/Pic5.jpg");
    }

    protected void onPostExecute(Long... result) {
        if(bitmap != null) {
            ImageView img = (ImageView) findViewById(R.id.imageView);
            img.setImageBitmap(bitmap);
        }
    }
}

AsyncTask is made to let a piece of code run on a different thread to prevent UI lag and performance of your app. For more information about AsyncTasks: Android Docs.

  • Forum posts: 21

Nov 17, 2014 1:26:31 PM via Website

I changed what you asked me but now it seams that the function onPostExecute is never activated. For not having an error on doInBackground function I created a Long and gave it the value 0 and returned it. How can I get the onPostExecute to be called?

  • Forum posts: 118

Nov 17, 2014 1:30:21 PM via Website

Oh frick, my bad.

In the constructor of onPostExecute, replace Long... with Long, so you simply have to remove the dots. It would look like this:

protected void onPostExecute(Long result)
  • Forum posts: 118

Nov 17, 2014 2:59:29 PM via Website

Itzick Binder

Thanks man! It works! You ROCK!

I'm glad to hear that it works :)

  • Forum posts: 1

Mar 30, 2015 11:12:03 AM via Website

image

I'm trying to create an application that on one of its activities it downloads images from a remote server to the user's device.
one error in this..?

  • Forum posts: 10

Apr 27, 2015 1:29:51 AM via Website

Why not just use a new thread to download the file? You dont need async really.