0

Below is the code snippet I used to fetch a image from a url and display it subsequently.

public Bitmap downloadFile(String fileUrl){
        URL myFileUrl =null;          
        try {
             myFileUrl= new URL(fileUrl);
        } catch (MalformedURLException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
        }
        try {
             HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
             conn.setDoInput(true);
             conn.connect();
             InputStream is = conn.getInputStream();

            Bitmap bmImg = BitmapFactory.decodeStream(is);
        } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
        }
       
        return bmImg;
   }

But I could not fetch the image. I am getting java.io.FileNotFoundException: http://test.com/test.jpg.

Any idea what's wrong with my code? Is there any other way to fetch a image from a url?

Nimantha
  • 5,793
  • 5
  • 23
  • 56
aandroidtest
  • 1,455
  • 7
  • 39
  • 67

2 Answers2

2

Try This Code it will work 100%. on your activity call below async class and pass your URL-

new GetImageFromUrl().execute(userImageUrl);

And this is my Async Class-

 public class GetImageFromUrl extends AsyncTask<String, Void, Bitmap> {
    @Override protected Bitmap doInBackground(String... urls) {
        Bitmap map = null; for (String url : urls) { 
            map = downloadImage(url);
            } 
        return map;
        }
    // Sets the Bitmap returned by doInBackground
    @Override
    protected void onPostExecute(Bitmap result) { 
        imageProfile.setImageBitmap(result);
        } // Creates Bitmap from InputStream and returns it
    private Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1; 
        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(stream, null, bmOptions); stream.close(); 
            }
        catch (IOException e1) {
            e1.printStackTrace(); 
            }
        return bitmap;
        } // Makes HttpURLConnection and returns InputStream
    private InputStream getHttpConnection(String urlString)
            throws IOException { 
        InputStream stream = null; 
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();
try { 
    HttpURLConnection httpConnection = (HttpURLConnection) connection; 
    httpConnection.setRequestMethod("GET"); 
    httpConnection.connect(); 
    if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
    { stream = httpConnection.getInputStream(); 
    }
    }
catch (Exception ex) { 
    ex.printStackTrace();
    }
return stream;
}
    }

You can check this link also where I am getting Image from gmail and display into ImageView- http://www.androidhub4you.com/2013/09/google-account-integration-in-android.html

Manish Srivastava
  • 1,810
  • 2
  • 15
  • 23
  • Your soln works but the issue is, for some urls it crashes. This is the weird part, not sure why it works for some url but crashes for others. But all the urls loads without any issue on a desktop web browser. – aandroidtest Oct 16 '13 at 06:33
  • Okay can you please paste your log cat when it got crash? I think problem with URL or may be you have network problem in your device. mean low data connectivity. you can check it before hit service. – Manish Srivastava Oct 16 '13 at 06:38
  • I am 110% sure it is working code. If URL and network is Okay. Please check and update me. and if it is work for you please accept my answer. – Manish Srivastava Oct 16 '13 at 06:44
  • The logcat shows "java.lang.runtimeException: An error occured while executing doInBackground()...." And this only happens for some URLs for some it works without any issue. – aandroidtest Oct 16 '13 at 06:55
  • If you don't mind You can send me demo code at my email-id And 2 URL one running and other which one being crash. manishupacc@gmail.com – Manish Srivastava Oct 16 '13 at 06:58
  • Ok i noticed that it only crashes if the image I am downloading is *.jpg, it works perfectly for *.jpeg and *.png. Have u encountered this before? – aandroidtest Oct 16 '13 at 07:12
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/39323/discussion-between-aandroidtest-and-manish-srivastava) – aandroidtest Oct 16 '13 at 07:27
0

For any sort of downloading in your Android App, you should use Async Task, Services , etc.

You can Use the Sample Async Class Template:

// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {

private Context context;

public DownloadTask(Context context) {
    this.context = context;
}

@Override
protected void onPostExecute(String result) {
    mProgressDialog.dismiss();
    if (result != null)
        Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
    else
        Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
        //HERE DISPLAY THE IMAGE TO THE DESIRED IMAGE VIEW
}

@Override
protected String doInBackground(String... sUrl) {
    // take CPU lock to prevent CPU from going off if the user 
    // presses the power button during download
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
         getClass().getName());
    wl.acquire();

    try {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report 
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                 return "Server returned HTTP " + connection.getResponseCode() 
                     + " " + connection.getResponseMessage();

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            output = new FileOutputStream("/sdcard/myImage.jpg");

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled())
                    return null;
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } 
            catch (IOException ignored) { }

            if (connection != null)
                connection.disconnect();
        }
    } finally {
        wl.release();
    }
    return null;
}
}

You can simply use this class for downloading your Image File:

final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("http://www.myextralife.com/wp-content/uploads/2008/08/stack-overflow-grave-scene.jpg");

You will know about the download status of the file in the onPoseExecute(...) Method, where you can simply display your downloaded image to the ImageView that you want.
Source:Download a file with Android, and showing the progress in a ProgressDialog
I hope this helps.

Community
  • 1
  • 1
Salman Khakwani
  • 6,634
  • 7
  • 32
  • 58