6

Good Morning All !!!!

I am trying to display images in Imageview. But My requirement is ,i need to display images in Drawable Integer Format.I am getting data from Server and getting image in url format..

For ex :http://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg

I want to convert this image in Drawable Format.

This is My code

This is my Interface

 public interface ECCardData<T> {

    @DrawableRes
    Integer getMainBackgroundResource();

    @DrawableRes
    Integer getHeadBackgroundResource();

    List<T> getListItems();
}

My Getter and Setter

     private Integer headBackgroundResource;

public Integer getHeadBackgroundResource() {
        return headBackgroundResource;
    }

    public void setHeadBackgroundResource(Integer headBackgroundResource) {
        this.headBackgroundResource = headBackgroundResource;
    }

This code where i set images

Integer drawableRes = dataset.get(position).getHeadBackgroundResource();
    if (drawableRes != null) {
        headView.setHeadImageBitmap(BitmapFactory.decodeResource(pagerContainer.getResources(), drawableRes, new BitmapFactoryOptions()));
    }

This is my parsing

 public static ArrayList<CardData> ParseCraft(String response) throws JSONException {


        ArrayList<CardData> alUser = new ArrayList<>();

        JSONObject jsonRoot = new JSONObject(response);

        JSONArray parentArray = jsonRoot.getJSONArray("products");

        for (int j = 0; j < parentArray.length(); j++) {

            JSONObject finalObject = parentArray.getJSONObject(j);

            CardData user = new CardData();

            user.setHeadTitle(finalObject.getString("product"));
            user.setPersonName(finalObject.getString("product_code"));

            JSONObject productJsonObject = finalObject.getJSONObject("main_pair");
            JSONObject productJsonObject1 = productJsonObject.getJSONObject("detailed");

            user.setHeadBackgroundResource(productJsonObject1.getString("image_path"));



            alUser.add(user);
        }

        return alUser;
    }

My json response

{
"products": [
    {
        "product_id": "863",
        "product": "LAVA 4G CONNECT M1",
        "company_name": "SAPTHAGIRI MOBILES",
        "age_verification": "N",
        "age_limit": "0",
        "product_code": "SGMM00044",
        "product_type": "P",
        "status": "A",
        "company_id": "34",
        "approved": "Y",
        "list_price": "0.00",
        "amount": "2",
        "weight": "0.000",
        "length": "0",
        "width": "0",
        "height": "0",
        "shipping_freight": "0.00",
        "low_avail_limit": "0",
        "timestamp": "1492758588",
        "updated_timestamp": "1500273558",
        "usergroup_ids": "0",
        "is_edp": "N",
        "edp_shipping": "N",
        "unlimited_download": "N",
        "tracking": "B",
        "free_shipping": "N",
        "zero_price_action": "R",
        "is_pbp": "N",
        "is_op": "N",
        "is_oper": "N",
        "is_returnable": "Y",
        "return_period": "10",
        "avail_since": "0",
        "out_of_stock_actions": "N",
        "localization": "",
        "min_qty": "0",
        "max_qty": "0",
        "qty_step": "0",
        "list_qty_count": "0",
        "tax_ids": "",
        "options_type": "P",
        "exceptions_type": "F",
        "details_layout": "default",
        "shipping_params": "a:5:{s:16:\"min_items_in_box\";i:0;s:16:\"max_items_in_box\";i:0;s:10:\"box_length\";i:0;s:9:\"box_width\";i:0;s:10:\"box_height\";i:0;}",
        "facebook_obj_type": "activity",
        "buy_now_url": "",
        "cod": "N",
        "price": "3094.000000",
        "category_ids": [
            295
        ],
        "position": "0",
        "seo_name": "lava-4g-connect-m1",
        "seo_path": "166/234/295",
        "average_rating": null,
        "discussion_type": "D",
        "discussion_thread_id": "619",
        "main_category": 295,
        "main_pair": {
            "pair_id": "2577",
            "image_id": "0",
            "detailed_id": "3266",
            "position": "0",
            "detailed": {
                "object_id": "863",
                "object_type": "product",
                "image_path": "http://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg",
                "alt": "",
                "image_x": "635",
                "image_y": "476",
                "http_image_path": "http://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg",
                "https_image_path": "https://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg",
                "absolute_path": "/home/mymartmycart/public_html/images/detailed/3/4G_CONNECT_M1.jpeg",
                "relative_path": "detailed/3/4G_CONNECT_M1.jpeg"
            }
        },
        "base_price": "3094.000000",
        "selected_options": [],
        "has_options": false,
        "product_options": [],
        "discounts": {
            "A": 0,
            "P": 0
        },
        "product_features": [],
        "qty_content": []
    }
Harshal Deshmukh
  • 1,787
  • 3
  • 14
  • 25
  • this might be some help : https://stackoverflow.com/questions/3375166/android-drawable-images-from-url – Gregorius Giovanni Roswin Aug 23 '17 at 04:15
  • 1
    @harshaldeshmukh if you just wanted to show the image coming from server url inside your imageview you can use glide or picaso library to display it directly to imageview – Snehal Gongle Aug 23 '17 at 04:15
  • 1
    @harshal you can also convert your url into bitmap and set the bitmap to your imageview here is a link to convert url to bitmap https://stackoverflow.com/questions/11831188/how-to-get-bitmap-from-a-url-in-android – Snehal Gongle Aug 23 '17 at 04:21
  • ok. let me try this one – Harshal Deshmukh Aug 23 '17 at 04:22
  • But when static images i set it display with above code?@ Snehal Gongle Now, I have to display server images .Please Check my interface code above – Harshal Deshmukh Aug 23 '17 at 04:25
  • `R.drawable.something` is a resource ID created during compilation time and you cannot "add" / "convert" the downloaded image into `R.drawable`, your interface design is wrong - you should use `android.graphics.drawable.Drawable` concept instead – pskink Aug 23 '17 at 04:50
  • @HarshalDeshmukh look you have to remove your this code and place glide code user.setHeadBackgroundResource(productJsonObject1.getString("image_path")); Glide.with(context) .load(url) .into(imageView); – Snehal Gongle Aug 23 '17 at 05:05
  • why you want this if you want to set the image you can use picasso – Abhijit Chakra Aug 23 '17 at 06:14

6 Answers6

4

This code is working for me to convert Server image url into Bitmap

 String drawableRes="http://kartpay.biz/api/v1/file/banner/IHMOcSHU7yoTVOkwYi1bOOz8shrXXrJhayCPFO17.jpeg"
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        try {
            URL url = new URL(drawableRes);
            headView.setHeadImageBitmap(BitmapFactory.decodeStream((InputStream)url.getContent()));
        } catch (IOException e) {
            //Log.e(TAG, e.getMessage());
        }
Harshal Deshmukh
  • 1,787
  • 3
  • 14
  • 25
2

you can doing this work in background with coroutines :

    private fun loadImageFromWebUrl(url: String?) {
    lifecycleScope.launch(Dispatchers.IO) {
        val image  = try {
            val iStream = java.net.URL(url).content as InputStream
            Drawable.createFromStream(iStream, "src name")
        } catch (e: Exception) {
            null
        }

        image?.let {
            withContext(Dispatchers.Main){
                imageView.setImageDrawable = image 
            }
        }
    }
}
WhoisAbel
  • 1,519
  • 1
  • 9
  • 19
0

i think that is not possible to convert image url i to drawable int

you can use lib to show image from url try this

1. glide

you can use Glide library to load image from url look the below code it can help you in simple way

compile this library

  compile 'com.github.bumptech.glide:glide:4.0.0'

than load image like this

RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_placeholder);
requestOptions.error(R.drawable.ic_error);

Glide.with(context)
     .setDefaultRequestOptions(requestOptions)
     .load(mainMenuDataModelArrayList.get(position)
     .getIMG()).into(holder.imageView);

2. use picasso

compile this library

compile 'com.squareup.picasso:picasso:2.5.2'

than load image like this

Picasso.
  with(context).
  load(url).
  into(imageview);

or try this

 new DownloadImage(imamgeview).execute(url);

create a Async Task

public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;

public DownloadImage(ImageView bmImage) {
    this.bmImage = (ImageView ) bmImage;
}

protected Bitmap doInBackground(String... urls) {
    String urldisplay = urls[0];
    Bitmap mIcon11 = null;
    try {
        InputStream in = new java.net.URL(urldisplay).openStream();
        mIcon11 = BitmapFactory.decodeStream(in);
    } catch (Exception e) {
        Log.d("Error", e.getStackTrace().toString());

    }
    return mIcon11;
}

protected void onPostExecute(Bitmap result) {
    bmImage.setImageBitmap(result);
}
}
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
  • I already try Glide and Picasso , its not showing image . I am Using Ramotion Expandable Collection Animation Library. In this, Only Integer image declare as per provided code above. Before here static images set ex.R.Drwable.Image1 .But now i want to set it dynamic – Harshal Deshmukh Aug 23 '17 at 04:20
  • Which Exception share it – AskNilesh Aug 23 '17 at 04:44
  • How to convert String Image_url into resource_id @Nilesh. I tried solution on web but not working? this is my url_image : http://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg this solution i tried int resID = pagerContainer.getResources().getIdentifier(drawableRes , "drawable", dataset.get(position).getHeadBackgroundResource()); @ Snehal Gongle please help – Harshal Deshmukh Aug 24 '17 at 12:08
0

You can download image from server URL to your image view by below code

public static Drawable LoadImageFromWebURL(String url) {
try {
    InputStream iStream = (InputStream) new URL(url).getContent();
    Drawable drawable = Drawable.createFromStream(ist, "src name");
    return drawable;
} catch (Exception e) {
    return null;
}}

you can also use third party library to download image into direct imageView

compile 'com.squareup.picasso:picasso:2.5.2'

Picasso.with(context).load("image web url").into(imageView);
vishal jangid
  • 2,967
  • 16
  • 22
0

I modified this library to do that. https://github.com/upendra-bajpai/expanding-collection-network/ if you are having any difficulty you can file an issue there. instead of resource data, you can pass URL there.

upendra
  • 21
  • 1
  • 4
  • A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted](//stackoverflow.com/help/deleted-answers). – rizerphe Dec 02 '20 at 09:13
-1

Can use Picasso library:

add gradle:

compile 'com.squareup.picasso:picasso:2.5.2'

Picasso.with(context).load("http://www.mymartmycart.com/images/detailed/3/4G_CONNECT_M1.jpeg").into(imageView);

more info http://square.github.io/picasso/

Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98