Search code examples
androidgridviewandroid-asynctaskcustom-adapter

Android how to use picasso with GridView?


I am trying to use the Picasso library in order to load movie posters from the TMDB API into a grid view using an AsyncTask so I used a custom adapter, but nothing happens, so I tried loading a single hardcoded image, but it didn't load also. I put a breakpoint in the "getView" method of my custom adapter and noticed it never fires... So, what am I doing wrong here?

This is my custom adapter:

public class MoviesAdapter extends ArrayAdapter<MovieEntity> {
    private Context context;
    private List<MovieEntity> movies = new ArrayList<>();

    public MoviesAdapter(Context context, int resource, int textViewResourceId, List<MovieEntity> objects) {
        super(context, resource, textViewResourceId, objects);
        this.context = context;
    }

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

    @Override
    public MovieEntity getItem(int position) {
        return movies.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView view = (ImageView) convertView;
        if (view == null) {
            view = new ImageView(context);
            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
        }

        MovieEntity movieEntity = getItem(position);

        Picasso.with(context)
                .load(movieEntity.moviePoster)
                .placeholder(R.drawable.placeholder)
                .error(R.drawable.error)
                .fit()
                .tag(context)
                .into(view);

        return view;
    }
}

and this is my code in the "onCreateView" method:

mMoviesAdapter = new MoviesAdapter(getActivity(),
                R.layout.grid_view_image_item,
                R.id.img_movie_poster,
                new ArrayList<MovieEntity>());

        GridView gridView = (GridView) rootVoew.findViewById(R.id.grid_movies);
        gridView.setAdapter(mMoviesAdapter);

The data is being set in the AsyncTask onPostExecute method like this:

protected void onPostExecute(String[] strings) {
            if (strings != null) {
                mMoviesAdapter.clear();
                mMoviesAdapter.addAll(strings);
            }
        }

What am I doing wrong here that there are no images in my grid view ?


Solution

  • I don't know if this is the most optimal solution, but it works in my case. I just removed the

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

    from the custom adapter and it probably had its own getCount...