I have an image button and would like to set background image from internet URL. I don't want to save background picture into SD card instead my image button's image needs to be URL. How can I do that in Android
Asked
Active
Viewed 9,229 times
0
-
You need to download it into a bitmap variable, and then set it as background image. Android is not a browser in which you could do that functionality you'd like to achieve. – abbath Mar 04 '13 at 11:15
-
i think your answer is here http://stackoverflow.com/questions/2471935/how-to-load-an-imageview-by-url-in-android – Mudassar Shaheen Mar 04 '13 at 11:24
-
@MudassarShaheen i think one comment is enough of same Link :) – Usman Kurd Mar 04 '13 at 12:22
3 Answers
0
Never tried this but hope fully this will work with you
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, saveFilename);
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
and for image view
ImageView IV= (ImageView)findViewById(R.id.imageId);
Drawable drw = ImageOperations(this,url,filename)
IV.setBackgroundDrawable(drw)
get URL
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}

Usman Kurd
- 7,212
- 7
- 57
- 86
0
Try this
Bitmap bitmap;
class loadImage extends AsyncTask<Void , Void, Void>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
URL url = new URL(stringURL);
URI uri = new URI(url.getProtocol(), url.getHost(),
url.getPath(), url.getQuery(), null);
HttpURLConnection connection = (HttpURLConnection) uri
.toURL().openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = input.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
byte[] img = byteBuffer.toByteArray();
byteBuffer.flush();
byteBuffer.close();
input.close();
bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ImageButton image_btn = (ImageButton)findViewById(R.id.your_image_button_id);
image_btn.setImageBitmap(bitmap);
}
}

AnujMathur_07
- 2,586
- 2
- 18
- 25
0
First you have to download your Image as Drawable: Android Drawable Images from URL
and after that set it as background drawable
button.setBackgroundDrawable(drawable)