1

I am trying to use async requests to fetch the images from urls, to prevent the url from hanging. This is the piece of code i am using for this

private void setImg(final ImageView im, String url){
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(url, new AsyncHttpResponseHandler(){
        public void onSuccess(String response){
            try{
                byte[] imageAsBytes = response.getBytes();
                im.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
                im.refreshDrawableState();
            } catch(Throwable e){
                e.printStackTrace();
            }
        }
    });
}

This is always showing this warning in logcat

12-29 01:55:33.043: D/skia(14414): --- SkImageDecoder::Factory returned null

I cannot find a proper reason for this. Any help?

4
  • Given the fact that Android already provide everything handy (HttpClient and AsyncTask) and it is quite straightforward to implement, what's the point of creating/using this extra third party Library AsyncHttpClient. By doing this, you put your own app in the risk that depend on other people's work, do you know how well they maintain their project? Do it yourself. Commented Dec 28, 2011 at 20:55
  • its an actively maintained project, and its providing me with a lot of abilities, that are will take me a lot of time to start from scratch. Commented Dec 28, 2011 at 21:05
  • Have you checked that 1) the bytes you retrieve actually represent an image (and not e.g. some unresolved redirect or html content), and 2) you're not trying to read the content (usually an InputStream) of the http response in your AsyncHttpClient twice? Commented Dec 28, 2011 at 21:16
  • 1. what does onSucess means ? response fully, FULLY arrived or just 200 ok ? if it's only 200 ok does your http client has other callbacks that give u extra bytes ? 2. can you try to write the bytes to the disk and compare them with a hex editor to the image u'll download using curl and the like ? 3. could it be the image is too big and you should use 'Options' clss to make it smaller uppon parsing ? Commented Jan 10, 2012 at 19:48

5 Answers 5

5

Now that a binary response handler has been added to AsyncHttp you can simply use androids BitmapFactory.decodeByeArray function:

AsyncHttpClient client = new AsyncHttpClient();
client.get(image_url, null, new AsyncHttpResponseHandler() {            
    @Override
    public void onSuccess(byte[] fileData) {
        Bitmap image = BitmapFactory.decodeByteArray(fileData, 0, fileData.length);
        //Do whatever you want with the image variable    
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

onSuccess(byte[] fileData) does not override any of the methods from the supertype. This does not work and will crash you application!
@CristyYG I fixed my issue by updating to version 1.4.9 of AsyncHttpClient loopj.com/android-async-http
1

I've been using lately the following library: UrlImageViewHelper. It uses an AsyncTask to download the image. Your code would be something like this:

private void setImg(final ImageView im, String url){
    UrlImageViewHelper.setUrlDrawable(im, url) ;
}

Very simple now, am I right?

Comments

1

If anyone is still working on this, here's how I am doing it

public static void setImg(final ImageView im, final String url){
    AsyncTask<Void, Void, Bitmap> t = new AsyncTask<Void, Void, Bitmap>(){
        protected Bitmap doInBackground(Void... p) {
            Bitmap bm = null;
            try {
                URL aURL = new URL(url);
                URLConnection conn = aURL.openConnection();
                conn.setUseCaches(true);
                conn.connect(); 
                InputStream is = conn.getInputStream(); 
                BufferedInputStream bis = new BufferedInputStream(is); 
                bm = BitmapFactory.decodeStream(bis);
                bis.close(); 
                is.close();
            } catch (IOException e) { 
                e.printStackTrace(); 
            }
            return bm;
        }

        protected void onPostExecute(Bitmap bm){
            Bitmap output = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(output);

            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bm.getWidth(), bm.getHeight());
            final RectF rectF = new RectF(rect);
            final float roundPx = 5;

            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bm, rect, rect, paint);
            im.setImageBitmap(output);
        }
    };
    t.execute();
}

Comments

1

[UPDATE] Image (and any binary data) response handling has been added to loopj's android-async-http library. Use the BinaryHttpResponseHandler

[old post] loopj's AsyncHttpClient does not yet support handling of byte[] responses. There's a fork that does, but it's a mess. So the answer is one of these:

A1) You don't.

A2) You use the fork provided via link via this link: https://github.com/loopj/android-async-http/issues/8

A3) You fork AsyncHttpClient, add byte[] handling (without tearing out String response handling, jesus!), and commit it back to the project. By doing this you will also receive open-source karma credits.

Comments

0

Android using async http connection to get image and text and show in a listView

public class MainActivity extends Activity {
    ListView list;
    public String IPadd = "http://api.gifts.com/v2/search/product.json?category=Nur&api_key=fd2ut5evb9jgzerjkeph54pz";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list=(ListView) findViewById(R.id.listView1);
        new AsyTask().execute(IPadd);
    }

    private class AsyTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... url) {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url[0]);
            // HttpPost httpPost=new HttpPost(url[0]);
            String text = null;
            try {
                HttpResponse response = httpClient.execute(httpGet);
                text = EntityUtils.toString(response.getEntity());

            } catch (Exception e) {
                return e.getLocalizedMessage();
            }

            return text;
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                JSONObject jObject = new JSONObject(result);
                JSONArray jarray = jObject.getJSONArray("products");
                for (int i = 0; i < jarray.length(); i++) {
                    ProductInfo p=new ProductInfo();
                    JSONObject jObj = jarray.getJSONObject(i);
                    p.setTitle(jObj.getString("title"));
                    p.setId(jObj.getString("price"));
                    p.setImage(jObj.getString("largeProductImageUrl"));
                    ProductInfo.arrayList.add(p);
                }
                ArrAdapter adapter=new ArrAdapter(getApplicationContext(),ProductInfo.arrayList);
                list.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }
}

    public class ArrAdapter extends BaseAdapter{

    TextView id,title;
    ImageView img;
    Context context;
    static ArrayList<ProductInfo> listitem=new ArrayList<ProductInfo>();
    public ArrAdapter(Context applicationContext,ArrayList<ProductInfo> arrayList) {
        this.context=applicationContext;
        listitem=arrayList;
    }

    @Override
    public int getCount() {
        return listitem.size();
    }

    @Override
    public Object getItem(int position) {
        return listitem.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ProductInfo p=listitem.get(position);
        if(convertView==null)
        {
            LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            convertView=inflater.inflate(R.layout.custom, null);
        }
        id=(TextView) convertView.findViewById(R.id.textView1);
        id.setText(p.getId());
        title=(TextView) convertView.findViewById(R.id.textView2);
        title.setText(p.getTitle());
        img=(ImageView) convertView.findViewById(R.id.imageView1);
        ImageLoader imageloader=new ImageLoader(img);
        imageloader.execute(p.getImage());
        return convertView;
    }

}

    public class ProductInfo {
    String ID,title,image;
    static ArrayList<ProductInfo> arrayList=new ArrayList<ProductInfo>();
    public void setId(String id)
    {
        this.ID=id; 
    }
    public String getId()
    {
        return ID;
    }
    public void setTitle(String tit)
    {
        this.title=tit; 
    }
    public String getTitle()
    {
        return title;
    }
    public void setImage(String img)
    {
        this.image=img; 
    }
    public String getImage()
    {
        return image;
    }

}

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

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    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) {

        }
        return mIcon11;
    }

    @Override 
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);

        bmImage.setImageBitmap(result);
     }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.