2

I have a small query, is it possible to get an image dynamically every-time the app is launched over the internet and then that Image can be used to be shown on UI(via xml file)please let me know if this can be achieved in android and with any sample code. Thanks & Regards.

3 Answers3

1

In this case the best way to do it is to load image via HTTP GET, store it in Bitmap object and inject programmatically into ImageView element defined in layout.

You can't override resource image so you cant use @drawable.

Here you have loadBitmap method that loads image by url and stores it in Bitmap: How to load an ImageView by URL in Android?

Next thing is to inject it into ImageView:

ImageView image = (ImageView) findViewById(R.id.image);
Bitmap bitmap = loadBitmap("http://www.android.com/images/logo.png");
image.setImageBitmap(bitmap);
Community
  • 1
  • 1
hsz
  • 148,279
  • 62
  • 259
  • 315
0

Not possible through XML.

I'd recommend having a placebo bitmap also in case there is no Internet access available at the time. Use AsyncTask when downloading.

new GetAndSetBitmap.execute(url)

private class GetAndSetBitmap extends AsyncTask<String, Void, Bitmap>
{
   protected Bitmap doInBackground(String... urls)
       {
          Bitmap bitmap = loadBitmap(url[0]);
          // Used the loadBitmap from other answer. Anything goes wrong 
          // load a local resource with the same dimensions.
          return bitmap;
       }
    @Override
       protected void onPostExecute(Bitmap bm)
       {
         yourImageView.setImageBitMap(bm);
       }
}
user1278085
  • 11
  • 1
  • 3
0

Guys found a better solution

try {
  ImageView i = (ImageView)findViewById(R.id.image);
  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
  i.setImageBitmap(bitmap); 
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}