0

I have an image view in my Android app, where I have to set a simple image from url. I tried the below code, but it doesn't set the image from url.

try {
        URL url = new URL("https://drive.google.com/...");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream stream = connection.getInputStream();
        Bitmap teamBmpImage = BitmapFactory.decodeStream(stream);
        teamImgView.setImageBitmap(teamBmpImage);
    }
    catch (Exception e) {

    }

Could someone guide me to achieve this please?

UPDATED CODE: Which gives Nullpointer exception

public class AboutActivity extends ActionBarActivity {
    ImageView teamImgView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_about);

        teamImgView = (ImageView) this.findViewById(R.id.teamImageView);
        new DownloadImageTask(teamImgView).execute("http://docs.oracle.com/javase/tutorial/2d/images/examples/strawberry.jpg");
    }

    class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            //pd.show();
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            //pd.dismiss();
            bmImage.setImageBitmap(result);
        }
    }
}
Lamorak
  • 10,957
  • 9
  • 43
  • 57
Stella
  • 1,728
  • 5
  • 41
  • 95
  • possible duplicate of [Best method to download image from url in Android](http://stackoverflow.com/questions/18210700/best-method-to-download-image-from-url-in-android) – Lamorak Apr 26 '15 at 19:50
  • No solution from this link worked out, that's why created new question – Stella Apr 26 '15 at 20:07
  • There actually are several good tips in the answers, if you tried those you should mention it in your question and specify what went wrong – Lamorak Apr 26 '15 at 20:12
  • I tried the async task samples, in my code throwing error as: 04-27 03:38:43.933 3034-3034/com.me.xyz.abc E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.me.xyz.abc, PID: 3034 java.lang.NullPointerException at com.me.xyz.abc.AboutActivity$DownloadImageTask.onPostExecute(AboutActivity.java:170) at com.me.xyz.abc.AboutActivity$DownloadImageTask.onPostExecute(AboutActivity.java:139) at android.os.AsyncTask.finish(AsyncTask.java:632) at android.os.AsyncTask.access$600(AsyncTask.java:177) – Stella Apr 27 '15 at 08:08
  • Well that is not very helpful without the code. There is a `NullPointerException` on line 170 of `AboutActivity`. Image downloading is quite complex task on android, I would suggest to use some library instead of handling it yourself if you don't know what you are doing. – Lamorak Apr 27 '15 at 08:13
  • I updated my full code in the question. – Stella Apr 27 '15 at 09:08
  • This code works for me, check `this.findViewById(R.id.teamImageView);` for null, it's the only thing that could cause the exception – Lamorak Apr 27 '15 at 11:16
  • Ok, I'll check that. – Stella Apr 27 '15 at 11:27
  • That was causing the issue, it works now thank you very much – Stella Apr 27 '15 at 11:48
  • I have an image from google drive. This link doesn't need any login authentication. it will work to anyone to download the image. When I am giving this url, the same code doesn't download and display image in imageview. https://drive.google.com/uc?export=download&id=0BzcFuGIeWflwZ25aeDdiVkJfNzA – Stella Apr 27 '15 at 19:27
  • That is not a link to the image, [this is](https://drive.google.com/uc?id=0BzcFuGIeWflwZ25aeDdiVkJfNzA). You have to remove `export=download` parameter from the URL – Lamorak Apr 27 '15 at 20:39

4 Answers4

2

I guess you are executing your code on the MainThread, which leads to a NetworkOnMainThreadException in android. Try to execute your code asynchronous like in the example below

new AsyncTask<String, Integer, Bitmap>() {

@Override
protected Bitmap doInBackground(String... params) {
    try {
        URL url = new URL(params[0]);
        return BitmapFactory.decodeStream(url.openConnection().getInputStream());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPostExecute(Bitmap bm) {
    ImageView teamImgView = (ImageView) findViewById(R.id.teamImageView);
    teamImgView.setImageBitmap(bm);
}
}.execute("https://drive.google.com/uc?....");
DonCalzone
  • 56
  • 3
  • have you added `` to your manifest? and can you post your stacktrace? – DonCalzone Apr 26 '15 at 20:23
  • Internet persmission is already there, because I'm using it for some other purposes. – Stella Apr 27 '15 at 05:29
  • Can you pls try this sample with this link, http://docs.oracle.com/javase/tutorial/2d/images/examples/strawberry.jpg – Stella Apr 27 '15 at 05:32
  • Did so, works fine. In your comment on your question you said that you get a nullpointer in line 170 (in onPostExecute). How does your code in line 170 looks like? When you followed my example either your ImageView is null (maybe you have set the wrong xml file as your contentView) or the bitmap is null, due to a exception in doInBackground. – DonCalzone Apr 27 '15 at 09:01
  • I've tried your code from your update and it works with the strawberry image, but not with your https google drive link. In both cases the app does not crash. Btw line 170 is commented out, so there cant occure a nullpointer. Guess i need to see the stacktrace – DonCalzone Apr 27 '15 at 09:35
  • Can you try with this url please? https://drive.google.com/uc?export=download&id=0BzcFuGIeWflwVUlqNWRzWWwwdVk – Stella Apr 27 '15 at 09:46
  • For me its crashing on emulator even with strawberry image. I am testing on Genymotion emulator. – Stella Apr 27 '15 at 09:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/76344/discussion-between-doncalzone-and-stella). – DonCalzone Apr 27 '15 at 10:19
  • I have an image from google drive. This link doesn't need any login authentication. it will work to anyone to download the image. When I am giving this url, the same code doesn't download and display image in imageview. https://drive.google.com/uc?export=download&id=0BzcFuGIeWflwZ25aeDdiVkJfNzA – Stella Apr 27 '15 at 19:28
1

You can use Picasso library and here is a detailed tutorial on how to do this.

This is very simple example usage

Picasso.with(activityContext)
    .load("https://drive.google.com/uc?....")
    .placeholder(R.drawable.image_name)
    .into(imageView);
Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
0

As bojan says you can use Picasso library wich handles many common pitfalls of image loading on Android.

Picasso.with(context).load("http://myurl/myImage.png").into(imageView);

Picasso

Anyway, check out this threat too :)

How to load an ImageView by URL in Android?

Community
  • 1
  • 1
JaimeToca
  • 46
  • 1
  • 5
0

Try following this link: http://www.tutorialsbuzz.com/2014/11/android-volley-url-imageview.html

This will help you to load your image using Volley library which will do all the networking stuff on networking thread and set your image on main UI thread. It has also the LRUCache part which you can skip if you want.