Загрузка изображений из URL-адресов с помощью Picasso в GridView

Я пытаюсь загрузить изображения в GridViewиспользование Picasso на заказ ArrayAdapter. Может ли кто-нибудь помочь мне найти проблему в моем коде? Сейчас я использую кнопку Обновить для вызова FetchWeatherTask.

Моя Основная Деятельность:

public class MainActivity extends AppCompatActivity {

private static final String MAINFRAGMENT_TAG = "MainFrgament";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ActionBar menu = getSupportActionBar();
    menu.setIcon(R.mipmap.ic_launcher);
    menu.setDisplayShowHomeEnabled(true);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new MainFragment(), MAINFRAGMENT_TAG)
                .commit();
    }
}
}

Фрагмент:

public class MainFragment extends Fragment {


static public PosterArrayAdapter adapter;
static public GridView movieGrid;
static public ArrayList<String> imagesPosters;
static public List<MovieClass> movies;

public MainFragment() {
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true); 
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.refresh_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int iD = item.getItemId();
    if (iD == R.id.refresh) {

        FetchMovieDataTask downloadTask = new FetchMovieDataTask();
        downloadTask.execute("popularity.desc"); //second option is "rating.desc"
        movieGrid.setAdapter(adapter);

        return true;
    }

    return super.onOptionsItemSelected(item);
}

// onCreateView - main task UI happens here

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.fragment_main, container, false);

    movieGrid = (GridView) rootview.findViewById(R.id.movies_grid);

    return rootview;
    }
}

FetchMovieDataTask:

public class FetchMovieDataTask extends AsyncTask<String, Void, String> { /* last String refers to String beofre DoInBackground */

    private final String MOVIEDATA_TAG = FetchMovieDataTask.class.getSimpleName();

    String movieJSONStr = null;

    @Override
    protected String doInBackground(String... params) {

        if (params.length == 0) {
            return null;
        }

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        try {

            final String FORECAST_BASE_URL = "http://api.themoviedb.org/3/discover/movie";
            final String SORTBY_PARAM = "sort_by";
            final String APPKEY_PARAM = "api_key";

            Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                    .appendQueryParameter(SORTBY_PARAM, params[0])
                    .appendQueryParameter(APPKEY_PARAM, BuildConfig.OPEN_MOVIES_API_KEY)
                    .build();

            URL url = new URL(builtUri.toString());

            Log.v(MOVIEDATA_TAG, "URL: " + builtUri.toString());

            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();

            if (inputStream == null) {
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {

                buffer.append(line + "n");
            }

            if (buffer.length() == 0) {

                return null;
            }

            movieJSONStr = buffer.toString();
            Log.v(MOVIEDATA_TAG, "Data: " + movieJSONStr);

        } catch (
                IOException e
                ) {
            Log.e("PlaceholderFragment", "Error ", e);
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceholderFragment", "Error closing stream", e);
                }
            } try {
                return String.valueOf(getMovieDataFromJson(movieJSONStr));
            } catch (JSONException e) {
                Log.e(MOVIEDATA_TAG, e.getMessage(), e);
                e.printStackTrace();
            }
            return movieJSONStr;
        }
    }

    /* JSON Parsing */

    private ArrayList<String> getMovieDataFromJson(String movieJSONStr)
            throws JSONException {

        final String ORIGINAL_TITLE = "original_title";
        final String POSTER_PATH = "poster_path";
        final String PLOT_SYNOPSIS = "overview";
        final String USER_RATING = "vote_average";
        final String RELEASE_DATE = "release_date";

        String BASIC_URL = "http://image.tmdb.org/t/p/w185/";

        JSONObject movieJson = new JSONObject(movieJSONStr);
        String movieInfo = movieJson.getString("results");
        JSONArray movieArray = new JSONArray(movieInfo);

        imagesPosters = new ArrayList<>(movieArray.length());
        MovieClass movieClassItem = new MovieClass();
        movies = new ArrayList<MovieClass>();

        for (int i = 0; i < movieArray.length(); i++) {

            JSONObject detail = movieArray.getJSONObject(i);

            String original_title = detail.getString(ORIGINAL_TITLE);
            String poster_path = detail.getString(POSTER_PATH);
            String plot_synopsis = detail.getString(PLOT_SYNOPSIS);
            String user_rating = detail.getString(USER_RATING);
            String release_date = detail.getString(RELEASE_DATE);
            movieClassItem.setPoster_path(poster_path);

            imagesPosters.add("http://image.tmdb.org/t/p/w185/" + poster_path);
            movies.add(movieClassItem);
        }
        for (String s : imagesPosters) {
            Log.v(MOVIEDATA_TAG, "Path: " + s);
        }
        Log.v(MOVIEDATA_TAG, "Array"+ imagesPosters.toString());
        return imagesPosters;
    }
}

MovieClass:

public class MovieClass implements Parcelable {

    String poster_path;

    public MovieClass() {
    }

    private MovieClass(Parcel parcel){
        poster_path = parcel.readString();
    }


    public String getPoster_path() {
        return poster_path;
    }


    public void setPoster_path(String poster_path) {
        this.poster_path = poster_path;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(this.poster_path);
    }

    public final Parcelable.Creator<MovieClass> CREATOR = new Parcelable.Creator<MovieClass>() {
        @Override
        public MovieClass createFromParcel(Parcel parcel) {
            return new MovieClass(parcel);
        }

        @Override
        public MovieClass[] newArray(int i) {
            return new MovieClass[i];
        }

    };
}

Пользовательский ArrayAdapter:

public class PosterArrayAdapter extends ArrayAdapter<MovieClass> {

    private final String LOG_TAG = PosterArrayAdapter.class.getSimpleName();

    public PosterArrayAdapter(Activity context, List<MovieClass> movieItems) {
        super(context, 0, movieItems);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        MovieClass movie = getItem(position);

        convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_view_item, parent, false);

        ImageView imagePoster = (ImageView) convertView.findViewById(imageView);
        Picasso.with(getContext()).load(imagesPosters.get(position)).into(imagePoster);

        return convertView;
    }
}

Фрагмент основной компоновки:

<?xml version="1.0" encoding="utf-8"?>
<GridView
    
    
    tools_context="com.example.martyna.popularmovies.MainFragment"
    android_id="@+id/movies_grid"
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_numColumns="2"
    android_verticalSpacing="0dp"
    android_horizontalSpacing="0dp"
    android_stretchMode="columnWidth"
    android_gravity="center_horizontal" />

Макет элемента GridView:

<FrameLayout
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent">

    <ImageView
        android_orientation="vertical"
        android_layout_width="200dp"
        android_layout_height="200dp"
        android_id="@+id/imageView"
        android_scaleType="centerCrop"
        tools_ignore="ContentDescription" />
</FrameLayout>

Спасибо за помощь!

1 ответ

  1. На самом деле, я разработчик Xamarin android, поэтому у меня мало знаний на Android. Я думаю, что вы должны передать список фильмов на адаптер, как..

    public PosterArrayAdapter(Activity context, List<MovieClass> movieItems) {
    super(context, 0, movieItems);
    MovieItems=movieItems;
    }

    А затем следует загрузить каждое изображение в Picasso.
    Picasso.with(getContext()).load(MovieItems[position]).into(imagePoster);

    Надеюсь, это поможет вам.
    Спасибо.