-1

I currently have an arraylist as follows:

private void loadImages() {
        images = new ArrayList<>();

        images.add(getResources().getDrawable(R.drawable.imag1));
        images.add(getResources().getDrawable(R.drawable.imag2));
        images.add(getResources().getDrawable(R.drawable.imag3));
}

I want to be able to convert a url into these drawables such that:

 drawable1 = "http.someimage.com/image.png"
 drawable2 = "http.someimage.com/newimage.png"

followed by

private void loadImages() {
            images = new ArrayList<>();

            images.add(getResources().getDrawable(drawable1));
            images.add(getResources().getDrawable(drawable2));
...etc    }

Is there any easy way to go around this? I definitely want to stick to drawables ,but I cant find any way to convert a url to drawable Any ideas? Thanks!

1 Answers1

0

If you have a URL of the picture you need to download it first.

You can't "convert" a URL into a drawable.

you need something like this:

URL url = new URL("http.someimage.com/image.png"); 
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());

Then if you need to add the image into an ImageView object you can call the method .setImageBitmap(bmp). Otherwise there are ways to extract a Drawable object from the Bitmap you can check this previous answer. then once you have the drawable you can add it to your arraylist.

Hope I got your question right

P.S.: be sure not to do this on main thread since it is a network operation! use a thread or an asynctask

Community
  • 1
  • 1
inno15
  • 31
  • 2
  • 1
    I did look at that answer but didnt work for me as expected.Can you show me with respect to my code for arraylist for a couple of images. –  Nov 05 '16 at 17:37
  • Once you obtain the Bitmap you need to convert it to a Drawable object. To make it for two images you just need to double the code snippet I posted you above. to convert Bitmaps to Drawables you can use [link](https://developer.android.com/reference/android/graphics/drawable/BitmapDrawable.html) – inno15 Nov 05 '16 at 17:54