Android async download images using Picasso in a list

I have a list in my android app that is used AppsAdapter

for each line. This adapter tries to download an image from the given URL and cache it. This is the code of the way to load the adapter image:

public View getView(int position, View convertView, ViewGroup parent) {
    this.parent = parent;
    View v;
    ViewHolder vh;
    v = buildView(convertView);
    vh = findViews(v);

    AppWithImage app = apps.get(position);

    setData(vh, app);
    return v;
}

private View buildView(View convertView) {
    View v;
    if (convertView != null) {
        v = convertView;
    } else {
        LayoutInflater vi = (LayoutInflater) this.context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate((listMode) ? R.layout.item_apps_list : R.layout.item_apps_grid, null);
    }
    return v;
}

private void setData(ViewHolder vh, AppWithImage app) {
    id = app.getId();
    vh.appTitle.setText(app.getName());
    vh.appRating.setRating((float) app.getRating());
    if (app.getIcon() != null) {
        vh.appIcon.setImage(app.getIcon());
    } else {
        vh.appIcon.setImage(noImageBitmap);
        if (app.getIcon_url() != null && !app.getIcon_url().equals("")) {
            loadBitmap(Constants.GET_IMAGE_ICON + app.getIcon_url());
        }
    }
    vh.appIcon.setHasShadow(!listMode);
    vh.id = app.getId();
}

Target target = new Target() {
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        // do something with the Bitmap
        onFileLoaded(id, bitmap);
    }

    @Override
    public void onBitmapFailed(Drawable drawable) {
        Log.i("Bitmap", "Bitmap failed");
    }

    @Override
    public void onPrepareLoad(Drawable drawable) {
        Log.i("Prepare", "Bitmap failed");
    }
};

public void loadBitmap(String url) {
    Picasso.with(context).load(url).into(target);
}

      

Since I am not using the Image View I need to use a Target instance that processes the bitmap for me and makes it material. The problem is that the first time I run the application, the method is onPrepareLoad

always called from Picasso, but nothing is returned from the url and therefore I have no images in my list.

Second time I run it, it works fine. Even if I scroll for the first time, android loads the images fine after they have finished loading.

I was looking into the Picasso source code and I saw that it triggers an action to load the bitmap of the url when the cache crashes and I think this is potentially my problem because when it loads a stream from the url the adapter and Target instances have largely disappeared.

How can I solve this to get a way onBitmapLoaded

?

+3


source to share





All Articles