androidandroid-imageviewandroid-drawableandroid-imageandroid-webservice

how do I transform a string of url's into drawable?


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!


Solution

  • 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