开发者

Android: Image Reading from URL

After seeing all the examples from net, i have written the follwoing code to read an image from the URL, show it to the Image view and save it to the path specified. public class Downloader {

public void startDownload(ImageView i, String path,String url){

    BitmapDownloaderTask task = new BitmapDownloaderTask(i,path);
    task.execute(url,null,null);
}
    static class FlushedInputStream extends FilterInputStream {
    public FlushedInputStream(InputStream inputStream) {
        super(inputStream);
    }

    @Override
    public long skip(long n) throws IOException {
        long totalBytesSkipped = 0L;
        while (totalBytesSkipped < n) {
            long bytesSkipped = in.skip(n - totalBytesSkipped);
            if (bytesSkipped == 0L) {
                  int b = read();
                  if (b < 0) {
                      break;  // we reached EOF
                  } else {
                      bytesSkipped = 1; // we read one byte
                  }
           }
  开发者_高级运维          totalBytesSkipped += bytesSkipped;
        }
        return totalBytesSkipped;
    }
}
static Bitmap downloadBitmap(String url) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) { 
            Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent(); 
                final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
                return bitmap;
            } finally {
                if (inputStream != null) {
                    inputStream.close();  
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {
        // Could provide a more explicit error message for IOException or IllegalStateException
        getRequest.abort();
        System.err.println("Error while retrieving bitmap from " + url +":"+ e.toString());
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}
private class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
    private String url;
    private final WeakReference<ImageView> imageViewReference;
    private String path;
    public BitmapDownloaderTask(ImageView imageView, String FilePath) {
        imageViewReference = new WeakReference<ImageView>(imageView);
        path = FilePath;
    }

    @Override
    // Actual download method, run in the task thread
    protected Bitmap doInBackground(String... params) {
         // params comes from the execute() call: params[0] is the url.
         return downloadBitmap(params[0]);
    }

    @Override
    // Once the image is downloaded, associates it to the imageView
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }

        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
        OutputStream outStream = null;
        File file = new File(path);
        try {
         outStream = new FileOutputStream(file);
         bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
         outStream.flush();
         outStream.close();
        }
        catch(Exception e)
        {}


    }
}

Now the problem is this code works sometimes and fails sometimes... the error is

    06-30 12:34:23.363: WARN/System.err(16360): Error while retrieving bitmap from https://URL IS HERE---REMOVE FOR PRIVACY:java.net.SocketTimeoutException: Read timed out

and some time a get SkImageDecoder::Factory returned null.

Help me with the possible reason


consider this example its show how to create image from url

               URL url = new URL(Your Image URL In String); 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap  myBitmap = BitmapFactory.decodeStream(input);
             yourImageView.setImageBitmap(myBitmap);


you should implement a retry when the connection was failed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜