Question

I wrote the following application to download an image from the internet and then display it in an imageview. But this appears to hang forever. Is it something to do with the speed of the internet (it is a small image, 340*340 pixels in size, and takes no time when I normally save it on my computer), or is there something wrong with the code?

package com.example.concurrency;

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;

public class UsingAsyncTask extends Activity {
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.using_asynctask); 
        String spec="http://www.google.com/imgres?imgurl=http%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F7%2F7a%2FBasketball.png&imgrefurl=http%3A%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile%3ABasketball.png&h=340&w=340&tbnid=EJmjEDyJzrhAuM%3A&zoom=1&docid=C_hn8nOgsGmuwM&hl=en&ei=Q0o2U93LNcaIygH4mICQBQ&tbm=isch&ved=0CHwQhBwwBg&iact=rc&dur=3875&page=1&start=0&ndsp=14";
        URL params = null;
        try {params= new URL(spec);} catch(Exception e) {}
        //Bitmap result;
        new MyTask().execute(params);
        imageView= (ImageView) findViewById(R.id.imageview);
    }

    private class MyTask extends AsyncTask<URL, Void, Bitmap> {

        private Bitmap loadImageFromNetwork(String url){
            try {
            Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
            return bitmap;
            } catch (Exception e) {
            e.printStackTrace();
            }
            return null;
        }

        /*protected void onPreExecute() {

        }*/

        @Override 
        protected Bitmap doInBackground(URL... params){
            //if(isCancelled()) return;
            String url=params[0].toString();
            final Bitmap bitmap= loadImageFromNetwork(url);
            return bitmap;
        }

        /*protected void onProgressUpdate(Progress progress){
            setProgressPercent(progress[0]);
        }*/

        @Override 
        protected void onPostExecute(Bitmap result){
            imageView.setImageBitmap(result);
        }

    }

}

Manifest File:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.concurrency"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.concurrency.UsingAsyncTask"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Layout:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >



<ProgressBar
    android:id="@+id/progressbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="4dip"
    android:indeterminate="false"
    android:max="10"/>

<ImageView
    android:id="@+id/imageview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="4dip"
    android:contentDescription="@string/imageview"/>

</LinearLayout>
Was it helpful?

Solution

I think you are using the Google image search URL, which it defintely will take more time to read. That image actual link is I mentioned below..use this direct link instead so it will load faster/better.

because it may take three or request in Google but it's a direct link for that file that's the reason....

http://upload.wikimedia.org/wikipedia/commons/7/7a/Basketball.png

And then use like this methods to read the images from Url.....

public static class BitmapWorkerTask extends
            AsyncTask<String, Void, Bitmap> {
        private int ht;
        private int wt;

        // Decode image in background.
        public BitmapWorkerTask(int progress, int ht, int wt) {
            this.ht = ht;
            this.wt = wt;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
                URL url;
                try {
                    url = new URL(string);
                    if (getBitmapFromMemCache(position) == null) {
                        HttpURLConnection connection = (HttpURLConnection) url
                                .openConnection();
                        connection.setConnectTimeout(4000);
                        connection.setReadTimeout(10000);
                        int v = connection.getContentLength() > 0 ? connection
                                .getContentLength() : 0;

                            if (v > 0) {
                                InputStream in = new BufferedInputStream(
                                        connection.getInputStream(), 32 * 1024);

                                Bitmap bitmap = decodeSampledBitmapFromResource(
                                        in, ht[i], wt[i]);


                } catch (MalformedURLException e) {
                    // e.printStackTrace();
                } catch (IOException e) {
                    // e.printStackTrace();
                }

            }
            return bitmap ;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            //Do your bitmap image setting....
                    //image.setImageBitmap(bitmap);
        }

    }

And this below methods are used to avoid the Out of memory exception....This will useful for you in high processing with images that's all...

    public static Bitmap decodeSampledBitmapFromResource(InputStream in,
            int reqWidth, int reqHeight) throws IOException {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        in.mark(in.available());
        BitmapFactory.decodeStream(in, null, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        in.reset();
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeStream(in, null, options);
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

OTHER TIPS

The problem is in spec string you pass to the AsyncTask. It is pointing to the HTML page, not to the image itself, that's why you can't decode InputStream to the Bitmap. Replace spec with the following value http://upload.wikimedia.org/wikipedia/commons/7/7a/Basketball.png. I tested this change and it works. Also please keep in mind, that if you are testing it on the emulator which is behind the proxy, you have to specify proxy settings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top