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
  • 6,405
  • 6
  • 28
  • 69
aandroidtest
  • 1,493
  • 8
  • 41
  • 68

1 Answers1

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,684
  • 7
  • 33
  • 58