It is a method to refer to the image file by URL and get it from the server. (Asynchronous processing)
Java
GetImagesUrl
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class ImageUrl extends AsyncTask<Integer, Integer, Bitmap> {
ImageView bmImage;
public ImageUrl(ImageView bmImage) {
this.bmImage = bmImage;
}
@Override
public Bitmap doInBackground(Integer... integers) {
Bitmap image;
URL imageUrl = null;
try {
//Change the URL to get with the argument number
//Let's define the URL of the image as a static variable
if (integers[0] == 0) {
imageUrl = new URL(Constants.Image1);
} else if (integers[0] == 1) {
imageUrl = new URL(Constants.Image2);
} else if (integers[0] == 2) {
imageUrl = new URL(Constants.Image3);
}
InputStream imageIs;
imageIs = imageUrl.openStream();
image = BitmapFactory.decodeStream(imageIs);
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
return image;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
main
int ImageNum;
//Get the target image with the numerical value contained in ImageNum and set it in ImageView
new ImageUrl((ImageView) view.findViewById(R.id.any_image)).execute(ImageNum);
Recommended Posts