I want to be able to use url's as image sources. I have found the following function to convert to bitmaps. However, I get a "NetworkOnMainThreadException." Using the Log i found that
conn.connect();
, is what is where the functions crashes.
I also found that because of the exception I should use an AsyncTask class extension. So I used it in the second section of code below. I still ended up with the same exception. I don't completely understand what the error means just that I am trying to do too many things in the same place at the same time.
Is there an easier way to turn a url into an image I can use? How can I fix the functions I have now?
public static Bitmap getImageBitmap(String url) {
Log.i("bitmap","here?");
Bitmap bm = null;
Log.i("bitmap","here?");
try {
Log.i("bitmap","here?");
URL aURL = new URL(url);
Log.i("bitmap","here?");
URLConnection conn = aURL.openConnection();
Log.i("bitmap","last ?");
conn.connect();
Log.i("bitmap","here?");
InputStream is = conn.getInputStream();
Log.i("bitmap","here?");
BufferedInputStream bis = new BufferedInputStream(is);
Log.i("bitmap","here?");
bm = BitmapFactory.decodeStream(bis);
bis.close();
Log.i("bitmap","here?");
is.close();
Log.i("bitmap","here?");
} catch (IOException e) {
Log.e("img", "Error getting bitmap", e);
}
return bm;
}
With AsyncTask:
class taskRunner extends AsyncTask<String, URL, Bitmap>{
public static Bitmap getImageBitmap(String url) {
Log.i("bitmap","here?");
Bitmap bm = null;
Log.i("bitmap","here?");
try {
Log.i("bitmap","here?");
URL aURL = new URL(url);
Log.i("bitmap","here?");
URLConnection conn = aURL.openConnection();
Log.i("bitmap","last ?");
conn.connect();
Log.i("bitmap","here?");
InputStream is = conn.getInputStream();
Log.i("bitmap","here?");
BufferedInputStream bis = new BufferedInputStream(is);
Log.i("bitmap","here?");
bm = BitmapFactory.decodeStream(bis);
bis.close();
Log.i("bitmap","here?");
is.close();
Log.i("bitmap","here?");
} catch (IOException e) {
Log.e("img", "Error getting bitmap", e);
}
return bm;
}
Thank you very much for taking the time to read this.