user6586661 user6586661 - 1 month ago 19
Android Question

Android get Images from Picasso to Bitmap Array

I want to get a Bitmap[] from my String[] with links. But this doesn't work as I want. I have this Method:

private Bitmap[] getBitmaps(String[] images){
ArrayList<Bitmap> temp = new ArrayList<>();
for(int i = 0; i < images.length; i++){
ImageView img = new ImageView(getContext());
FrameLayout.LayoutParams x = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
img.setLayoutParams(x);
Picasso.with(getContext()).load(MainPostAdapter.USER_URL+images[i]+".png").into(img, new Callback() {
@Override
public void onSuccess() {
temp.add(BitmapRes.drawableToBitmap(img.getDrawable()));
movableBackgroundContainer.removeView(img);
}

@Override
public void onError() {

}
});
movableBackgroundContainer.addView(img);
}
return temp.toArray(new Bitmap[temp.size()]);
}


The problem is I get a null Array because it adds the Bitmap to the list after the onSuccess function. How can I now wait until all onSuccess added the bitmaps and then return?

Answer

The get() function of Picasso does what you're looking for. It downloads a Bitmap rather than load an image into an ImageView. Note that Picasso's get() method cannot be called on the main thread. My examples uses and AsyncTask to download images on a separate thread.

    String[] images = new String[] {"http://path.to.image1.jpg", "http://path.to.image2.jpg"};
    new AsyncTask<String[], Void, List<Bitmap>>() {
        @Override
        protected List<Bitmap> doInBackground(String[]... params) {
            try {
                List<Bitmap> bitmaps = new ArrayList<Bitmap>();
                for (int i = 0; i < params[0].length; ++i) {
                    bitmaps.add(Picasso.with(getActivity()).load(params[0][i]).get());
                }
                return bitmaps;
            } catch (IOException e) {
                return null;
            }
        }

        @Override
        public void onPostExecute(List<Bitmap> bitmaps) {
            if (bitmaps != null) {
                // Do stuff with your loaded bitmaps
            }
        }
    }.execute(images);