0

I am trying to GET a Bitmap image from a URL.
(Example: https://cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png)

But there seems to be a problem with the connection.connect() line, that I can't figure out.
I have allowed internet access in the app.

public static Bitmap getBitmapFromURL(String src) {
    HttpURLConnection connection = null;
    InputStream inputStream = null;
    try {
        URL url = new URL(src);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.connect();
    }
    return BitmapFactory.decodeStream(inputStream);
}  
Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
Runesen
  • 1
  • 1
  • 2

2 Answers2

3

You could use glide for a short solution

    implementation "com.github.bumptech.glide:glide:4.11.0"
    annotationProcessor "com.github.bumptech.glide:compiler:4.11.0"
 try {
                        Bitmap bitmap = Glide
                                .with(context)
                                .asBitmap()
                                .load(imageUrl)
                                .submit()
                                .get();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
gowtham6672
  • 999
  • 1
  • 10
  • 22
0

Generally network connection should be done is a separate thread. You can use AsyncTaskfor that. For example, this works:

ImageView imageView;

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

    imageView = (ImageView) findViewById(R.id.imageView);
    new LoadImage().execute("https://cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png");
}

private class LoadImage extends AsyncTask<String, Void, Bitmap>{
       @Override
       protected Bitmap doInBackground(String... strings) {
           Bitmap bitmap = null;
           try {
               InputStream inputStream = new URL(strings[0]).openStream();
               bitmap = BitmapFactory.decodeStream(inputStream);
           } catch (IOException e) {
               e.printStackTrace();
           }
           return bitmap;
       }

       @Override
       protected void onPostExecute(Bitmap bitmap) {
           imageView.setImageBitmap(bitmap);
       }
   }
ruben
  • 1,745
  • 5
  • 25
  • 47