I have some images in my Servlet that I want to download into my Android app.
I am performing a GET request to this URL:
public static final String URL ="http://myIpAddress:8080/imgs";
And this class doing the job:
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
StaggeredPrenotaTour staggeredPrenotaView;
public GetXMLTask(StaggeredPrenotaTour listView){
this.staggeredPrenotaView = listView;
}
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
staggeredPrenotaView.pullTours(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
and in my Servlet:
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
InputStream st = getServletContext().getResourceAsStream("/WEB-INF/imgs/cardbackground9.jpg");
BufferedImage bi = ImageIO.read(st); **//error here**
OutputStream out = resp.getOutputStream();
//Todo send InputStream into OutputStream
ImageIO.write(bi, "jpg", out);
out.close();
}
I would like to receive an InputStream containing my Bitmap image but I receive the following error:
WARNING: Error for /imgs
java.lang.NoClassDefFoundError: javax.imageio.ImageIO is a restricted class.Please see the Google App Engine developer's guide for more details.
at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:51)
at madapps.bicitourbo.backend.MyServlet.doGet(MyServlet.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
...
Why do you need to use ImageIO? You can do simply something like:
InputStream st = getServletContext().getResourceAsStream("/WEB-INF/imgs/cardbackground9.jpg");
OutputStream os = resp.getOutputStream();
if (st != null) {
byte[] buf = new byte[4096];
int nRead;
while( (nRead=st.read(buf)) != -1 ) {
os.write(buf, 0, nRead);
}
st.close();
}
Related
I have an server (i use GlassFish). I am able to send Json or XML etc. with http to my android device. I saw an example to upload a picture from my android device to the server. That converts my picked image to byte, converts to String and back at my server. So i can put it on my PC (server).
Now i just want the opposite: get a picture from my PC and with the URL get the image (bitmap here) to imageview. but with debugging bmp seems to be "null". google says its because my image is not a valid bitmap (so maybe something is wrong at my server encoding?).
What does i need to change to this code to get it working?
Server code:
public class getImage{
String imageDataString = null;
#GET
#Path("imageid/{id}")
public String findImageById(#PathParam("id") Integer id) {
//todo: schrijf een query voor het juiste pad te krijgen!
System.out.println("in findImageById");
File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");
try{
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = Base64.encodeBase64URLSafeString(imageData);
imageInFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return imageDataString;
}
}
and this is the android side (android studio):
public class XMLTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
java.net.URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String line) {
super.onPostExecute(line);
byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
try {
Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
ivFoto.setImageBitmap(bmp);
}catch (Exception e){
Log.d("tag" , e.toString());
}
}
}
Have you tried HttpURlConnection?
Here's a sample code:
private class SendHttpRequestTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL("http://xxx.xxx.xxx/image.jpg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}catch (Exception e){
Log.d(TAG,e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
ImageView imageView = (ImageView) findViewById(ID OF YOUR IMAGE VIEW);
imageView.setImageBitmap(result);
}
}
I hope i could help
You can use Glide it is simplest way to load image
This is how you can save image
Glide.with(context)
.load(image)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
String name = new Date().toString() + ".jpg";
imageName = imageName + name.replaceAll("\\s+", "");
Log.d(TAG, "onResourceReady: imageName = " + imageName);
ContextWrapper contextWrapper = new ContextWrapper(mContext);
File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory, imageName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(myPath);
resource.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
and this is how you can read the image
ContextWrapper contextWrapper = new ContextWrapper(mContext);
File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
String path = directory.getAbsolutePath();
path = path + "/" + imageName;
Glide.with(mContext).load(path).into(your imageview);
Why don't you use Glide?
For build.gradle in your app module:
dependencies {
compile 'com.github.bumptech.glide:glide:3.7.0'
...
}
Then:
Glide
.with(context) // replace with 'this' if it's in activity
.load("http://www.google.com/.../image.gif")
.into(R.id.imageView);
Try using Base64.encodeBase64String(imageData) with out using the URLSafeString.
If there are people who are also trying to do it my way, this is working:
public class XMLTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
java.net.URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String line) {
super.onPostExecute(line);
byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
try {
Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
ivFoto.setImageBitmap(bmp);
}catch (Exception e){
Log.d("tag" , e.toString());
}
}
}
#Stateless
#Path("getImage")
public class getImage {
//todo: capture error inandroid + take just path!
String imageDataString = null;
#GET
#Path("imageid/{id}")
public String findImageById(#PathParam("id") Integer id) {
//todo: schrijf een query voor het juiste pad te krijgen!
System.out.println("in findImageById");
File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");
try{
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = Base64.encodeBase64String(imageData);
imageInFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return imageDataString;
}
}
I hope this code is useful.
go to your MainActivity.java and try this code:
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public void downloadImage(View view)
{
Log.i("Button","Tapped");
DownloadImage task = new DownloadImage();
Bitmap result = null;
try {
result = task.execute("https://vignette.wikia.nocookie.net/disney/images/0/0a/ElsaPose.png/revision/latest?cb=20170221004839").get();
}
catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
imageView.setImageBitmap(result);
}
public class DownloadImage extends AsyncTask<String, Void, Bitmap>
{
#Override
protected Bitmap doInBackground(String... imageurls) {
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(imageurls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream in =httpURLConnection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in);
return myBitmap;
}
catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView);
}
}
Don't forget to add this piece of code in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
I am new for android. I Want to get image from url and set into Bitmap variable.I tried so many code but i didn't get.
Here my code:
String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;
ImageDownloaderTask.java
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
Bitmap bImage;
#Override
public Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
private Bitmap downloadBitmap(String src) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(src);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + src);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
bImage = result;
}
}
Thanks in advance...
Here is code you can use
new DownloadImage().execute("https://www.google.com/intl/en_ALL/images/logo.gif");
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// Do whatever you want to do with the bitmap
}
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
From your code,
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;
you get an empty image because your ImageDownloaderTask not yet finished downloadin the image.
Try updating image on your onPosExecute:
protected void onPostExecute(Bitmap result) {
bImage = result;
// Update image here.
}
Bitmap bmp;
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
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;
}
protected void onPostExecute(Bitmap result) {
bmp=result
}}
try this,
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
In my opinion its best to create an interface for this:
public interface ImageDownloaderResponse {
void downloadFinished(Bitmap bm);
}
In your ImageDownloaderTask:
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
Bitmap bImage;
public ImageDownloaderResponse delegate = null;
#Override
public Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
private Bitmap downloadBitmap(String src) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(src);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + src);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
delegate.downloadFinished(result);
}
}
Then let your activity/fragment implement the interface like this:
public class MainActivity extends AppCompatActivity implements ImageDownloaderResponse {
And use your Downloadtask like this:
String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(url);
And add this to your activity/fragment:
#Override
public void downloadFinished(Bitmap bm) {
Bitmap bitmap = bm;
}
Try below code:
URL url = new URL("https://www.google.com/intl/en_ALL/images/logo.gif");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
And add this permission in manifest:
<uses-permission android:name="android.permission.INTERNET" />
I trying read a external imagen but I've the error
"android.os.NetworkOnMainThreadException" and
"http.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)"
OnCreate
imageView = (ImageView) findViewById(R.id.image_view);
downloadFile(imageHttpAddress);
Function downloadFile
void downloadFile(String imageHttpAddress) {
URL imageUrl = null;
try {
imageUrl = new URL(imageHttpAddress);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.connect();
loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
imageView.setImageBitmap(loadedImage);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error cargando la imagen: "+e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
From Android docs
You should not perform network operations on the UI thread.
To avoid this exception, you can use AsyncTask for your request.
imageView = (ImageView) findViewById(R.id.image_view);
new AsyncTask<String, Void, Bitmap>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... url) {
return downloadFile(url[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
}.execute(imageHttpAddress);
private Bitmap downloadFile(String imageHttpAddress) {
URL imageUrl = null;
try {
imageUrl = new URL(imageHttpAddress);
HttpURLConnection conn =(HttpURLConnection)imageUrl.openConnection();
conn.connect();
loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
return loadedImage;
} catch (IOException e) {
e.printStackTrace();
}
}
Even better, use some Async image handling library for android. there are many of these around the internet. A very popular one is picasso
You can use this function ;)
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch(Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap
}
i try to load image fro url and show imageview.i wrote code witch can download image and show it.but now i want to download facebook user image and show it.i know how i can check facebook user image "like this
http://graph.facebook.com/user id /picture?width=80&height=80
when i run programm i have RuntimeException
this is a my source
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
user_img.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
new GetXMLTask().execute((new String[] { URL }));
if my url would be for example http://mywebsite./pic.jpg then program working perfect but i want show facebook user image
You should be using picasso.
Add dependency into your project. And further just a singe line of code will do the task.
Picasso.with(context).load("http://somepath/someimage.png").into(imageView);
No need of writing thread and optimizing bitmaps.
You can refer : http://square.github.io/picasso/
I have this code to download a photo from a URL and display it in an ImageView on Android.
I am not sure how to loop this if I had a ArrayList or Array of multiple Urls to download and display on different ImageViews. I would appreciate any help or insight on how to proceed! Thank you!
public class DisplayPhotoTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
//sets bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
ImageView imageView1 = (ImageView) findViewById(R.id.imageView);
imageView1.setImageBitmap(result);
}
//creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
//makes httpurlconnection and returns inputstream
private InputStream getHttpConnection(String urlString) throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
You can for example make a result of AsyncTask as List ant write something like this
protected Bitmap doInBackground(String... urls) {
List<Bitmap> bitmaps = new ArrayList<Bitmap>;
for (String url : urls) {
bitmaps.add(downloadImage(url));
}
return bitmaps;
}
protected void onPostExecute(List<Bitmap> result) {
//...
}
But what I really would recommend you is to use Volley library written by Google, it has really easy and powerful API (here is Google I/O session about it https://developers.google.com/live/shows/474338138 and repository https://android.googlesource.com/platform/frameworks/volley/)