Udacity热门电影Stage 1 Issue

时间:2016-03-25 12:43:26

标签: android popularity

我的应用程序应该将TheMovieDB API中的热门电影照片提取到GridView中。

我已经构建了所有应用程序组件,剩下的是如何将照片加载到适配器阵列中,当它落在手机上时,怎么样?!

下面是我的片段代码。

public class PhotoGrid extends Fragment {

static String[] str1;
GridView gridView;

public PhotoGrid() {

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Add this line in order for this fragment to handle menu events.
    setHasOptionsMenu(true);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_refresh) {
        FetchMoviesPosters fetchMoviesPosters = new FetchMoviesPosters();
        fetchMoviesPosters.execute("popularity.desc");
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {



    View rootView = inflater.inflate(R.layout.fragment_photo_grid, container,        false);
    GridView gridView = (GridView) rootView.findViewById(R.id.grid_view);



    return rootView;
   }


  public class ImageAdapter extends BaseAdapter {

    private Context mContext;

    private String[] mThumbIds;

    public ImageAdapter(Context c,String[] str2) {

        mContext = c;
        mThumbIds=str2;
    }

    @Override
    public int getCount() {
        if(mThumbIds!=null)
        {
            return mThumbIds.length;
        }
        else
        {
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(500,500));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(4, 4, 4, 4);
        } else {
            imageView = (ImageView) convertView;
        }

        Picasso.with(mContext).load(mThumbIds[position]).into(imageView);

        //imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
        return imageView;
    }
   }
public class FetchMoviesPosters extends AsyncTask<String, Void, String[]> {
    private final String LOG_TAG = FetchMoviesPosters.class.getSimpleName();


    private String[] MoviesJasonPrase(String moviesPosterStr) throws       JSONException {

        final String Poster_Path = "poster_path";

        JSONObject moviesJson = new JSONObject(moviesPosterStr);
        JSONArray resultsArray = moviesJson.getJSONArray("results");

        String[] resultStrs = new String[0];
        for (int i = 0; i < resultsArray.length(); i++) {

            JSONObject indexObject = resultsArray.getJSONObject(i);
            String poster = indexObject.getString(Poster_Path);

            resultStrs[i] = poster; // Add each item to the list
        }
        for (String s : resultStrs) {
            Log.v(LOG_TAG, "Posters entry: " + s);
        }
        return resultStrs;

    }

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

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


        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        // Will contain the raw JSON response as a string.
        String moviePostersJsonStr = null;


        try {

            final String FORECAST_BASE_URL =
                    "https://api.themoviedb.org/3/discover/movie?";
            final String SORT_OPTI = "sort_by";
            final String APPID_PARAM = "api_key";

            Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                    .appendQueryParameter(SORT_OPTI, params[0])
                    .appendQueryParameter(APPID_PARAM,      BuildConfig.THE_MOVIE_DB)
                    .build();

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

            Log.v(LOG_TAG, "Built URI " + builtUri.toString());
            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            moviePostersJsonStr = buffer.toString();
        } catch (IOException e) {
            Log.e("PhotoGrid", "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PhotoGrid", "Error closing stream", e);
                }
            }

        }
        return null;
    }

         @Override
    protected void onPostExecute(String[] Strings) {
        if (Strings != null) {

            str1 = new String[Strings.length];
            for (int i = 0; i < Strings.length; i++) {
                String[] getImage=Strings[i].split("-");
                str1[i] = "http://image.tmdb.org/t/p/w185/" + getImage[0];
            }
            ImageAdapter adp = new ImageAdapter(getActivity(),str1);
            gridView.setAdapter(adp);

        }
    }
    }
}

这是我从API中获得的一部分我使用JSON格式来使其更清晰:

{  
  "page":1,
  "results":[  
     {  
       "poster_path":"\/6bCplVkhowCjTHXWv49UjRPn0eK.jpg",
        "adult":false,
        "overview":"Fearing the actions of a god-like Super Hero left   unchecked, Gotham City’s own formidable, forceful vigilante takes on Metropolis’s  most revered, modern-day savior, while the world wrestles with what sort of hero it really needs. And with Batman and Superman at war with one another, a new threat quickly arises, putting mankind in greater danger than it’s ever known   before.",
       "release_date":"2016-03-23",
        "genre_ids":[  
        28,
        12,
        14,
        878
     ],
     "id":209112,
     "original_title":"Batman v Superman: Dawn of Justice",
     "original_language":"en",
     "title":"Batman v Superman: Dawn of Justice",
     "backdrop_path":"\/vsjBeMPZtyB7yNsYY56XYxifaQZ.jpg",
     "popularity":51.416795,
     "vote_count":302,
     "video":false,
     "vote_average":5.8
     },
     {  
     "poster_path":"\/w93GAiq860UjmgR6tU9h2T24vaV.jpg",
     "adult":false,
     "overview":"With the nation of Panem in a full scale war, Katniss   confronts President Snow in the final showdown. Teamed with a group of her closest friends – including Gale, Finnick, and Peeta – Katniss goes off on a mission with the unit from District 13 as they risk their lives to stage an assassination attempt on President Snow who has become increasingly obsessed with destroying her. The mortal traps, enemies, and moral choices that await Katniss will challenge her more than any arena she faced in The Hunger Games.",
     "release_date":"2015-11-18",
     "genre_ids":[  
        28,
        12,
        18
     ],
     "id":131634,
     "original_title":"The Hunger Games: Mockingjay - Part 2",
     "original_language":"en",
     "title":"The Hunger Games: Mockingjay - Part 2",
     "backdrop_path":"\/qjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg",
     "popularity":39.643568,
     "vote_count":1326,
     "video":false,
     "vote_average":6.79
  },

2 个答案:

答案 0 :(得分:0)

使用Picasso或glide从服务器加载图像。毕加索检查一下 - http://square.github.io/picasso/

更新

尝试以下代码

电影详情的模型类

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.ToStringBuilder;


public class MovieDetailModel {

    @SerializedName("poster_path")
    @Expose
    private String posterPath;
    @SerializedName("adult")
    @Expose
    private Boolean adult;
    @SerializedName("overview")
    @Expose
    private String overview;
    @SerializedName("release_date")
    @Expose
    private String releaseDate;
    @SerializedName("genre_ids")
    @Expose
    private List<Integer> genreIds = new ArrayList<Integer>();
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("original_title")
    @Expose
    private String originalTitle;
    @SerializedName("original_language")
    @Expose
    private String originalLanguage;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("backdrop_path")
    @Expose
    private String backdropPath;
    @SerializedName("popularity")
    @Expose
    private Double popularity;
    @SerializedName("vote_count")
    @Expose
    private Integer voteCount;
    @SerializedName("video")
    @Expose
    private Boolean video;
    @SerializedName("vote_average")
    @Expose
    private Double voteAverage;

    /**
    *
    * @return
    * The posterPath
    */
    public String getPosterPath() {
    return posterPath;
    }

    /**
    *
    * @param posterPath
    * The poster_path
    */
    public void setPosterPath(String posterPath) {
    this.posterPath = posterPath;
    }

    /**
    *
    * @return
    * The adult
    */
    public Boolean getAdult() {
    return adult;
    }

    /**
    *
    * @param adult
    * The adult
    */
    public void setAdult(Boolean adult) {
    this.adult = adult;
    }

    /**
    *
    * @return
    * The overview
    */
    public String getOverview() {
    return overview;
    }

    /**
    *
    * @param overview
    * The overview
    */
    public void setOverview(String overview) {
    this.overview = overview;
    }

    /**
    *
    * @return
    * The releaseDate
    */
    public String getReleaseDate() {
    return releaseDate;
    }

    /**
    *
    * @param releaseDate
    * The release_date
    */
    public void setReleaseDate(String releaseDate) {
    this.releaseDate = releaseDate;
    }

    /**
    *
    * @return
    * The genreIds
    */
    public List<Integer> getGenreIds() {
    return genreIds;
    }

    /**
    *
    * @param genreIds
    * The genre_ids
    */
    public void setGenreIds(List<Integer> genreIds) {
    this.genreIds = genreIds;
    }

    /**
    *
    * @return
    * The id
    */
    public Integer getId() {
    return id;
    }

    /**
    *
    * @param id
    * The id
    */
    public void setId(Integer id) {
    this.id = id;
    }

    /**
    *
    * @return
    * The originalTitle
    */
    public String getOriginalTitle() {
    return originalTitle;
    }

    /**
    *
    * @param originalTitle
    * The original_title
    */
    public void setOriginalTitle(String originalTitle) {
    this.originalTitle = originalTitle;
    }

    /**
    *
    * @return
    * The originalLanguage
    */
    public String getOriginalLanguage() {
    return originalLanguage;
    }

    /**
    *
    * @param originalLanguage
    * The original_language
    */
    public void setOriginalLanguage(String originalLanguage) {
    this.originalLanguage = originalLanguage;
    }

    /**
    *
    * @return
    * The title
    */
    public String getTitle() {
    return title;
    }

    /**
    *
    * @param title
    * The title
    */
    public void setTitle(String title) {
    this.title = title;
    }

    /**
    *
    * @return
    * The backdropPath
    */
    public String getBackdropPath() {
    return backdropPath;
    }

    /**
    *
    * @param backdropPath
    * The backdrop_path
    */
    public void setBackdropPath(String backdropPath) {
    this.backdropPath = backdropPath;
    }

    /**
    *
    * @return
    * The popularity
    */
    public Double getPopularity() {
    return popularity;
    }

    /**
    *
    * @param popularity
    * The popularity
    */
    public void setPopularity(Double popularity) {
    this.popularity = popularity;
    }

    /**
    *
    * @return
    * The voteCount
    */
    public Integer getVoteCount() {
    return voteCount;
    }

    /**
    *
    * @param voteCount
    * The vote_count
    */
    public void setVoteCount(Integer voteCount) {
    this.voteCount = voteCount;
    }

    /**
    *
    * @return
    * The video
    */
    public Boolean getVideo() {
    return video;
    }

    /**
    *
    * @param video
    * The video
    */
    public void setVideo(Boolean video) {
    this.video = video;
    }

    /**
    *
    * @return
    * The voteAverage
    */
    public Double getVoteAverage() {
    return voteAverage;
    }

    /**
    *
    * @param voteAverage
    * The vote_average
    */
    public void setVoteAverage(Double voteAverage) {
    this.voteAverage = voteAverage;
    }

    @Override
    public String toString() {
    return ToStringBuilder.reflectionToString(this);
    }

}

适配器代码

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private List<MovieDetailModel> movieList = new ArrayList<MovieDetailModel>();

    public ImageAdapter(Context c, List<MovieDetailModel> mMovieList) {
        mContext = c;
        movieList = mMovieList;
    }

    public int getCount() {
        return movieList.size();
    }

    public Object getItem(int position) {
        return movieList.get(position);
    }

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

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  
     // if it's not recycled, initialize some    attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }


        if(!TextUtils.isEmpty(movieList.get(position).getPosterPath()))
            Picasso.with(mContext).load(movieList.get(position).getPosterPath()).into(imageView);

        //imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }


    // references to your images
    private Integer[] mThumbIds = {
    };
}

答案 1 :(得分:0)

以下是经过大量编辑后的代码,现在正在运行,海报显示

最后。

public class PhotoGrid extends Fragment {

String[] movieId, movieTitle, movieReleaseDate, movieVoteAverage,   movieOverview, moviePosterPath;
static String[] string1;
GridView gridView;

public PhotoGrid() {

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Add this line in order for this fragment to handle menu events.
    setHasOptionsMenu(true);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_refresh) {
        FetchMoviesPosters fetchMoviesPosters = new FetchMoviesPosters();
        fetchMoviesPosters.execute("popularity.desc");
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    View rootView = inflater.inflate(R.layout.fragment_photo_grid, container,   false);
    gridView = (GridView) rootView.findViewById(R.id.grid_view);
 //        gridView.setAdapter(imageAdapter);


    return rootView;
}


public class ImageAdapter extends BaseAdapter {

    private Context mContext;

    private String[] mThumbIds;

    public ImageAdapter(Context c, String[] str2) {

        mContext = c;
        mThumbIds = str2;
    }

    @Override
    public int getCount() {
        if (mThumbIds != null) {
            return mThumbIds.length;
        } else {
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(500, 500));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(4, 4, 4, 4);
        } else {
            imageView = (ImageView) convertView;
        }

        Picasso.with(mContext).load(mThumbIds[position]).into(imageView);

        //imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
        return imageView;
    }
}

    public class FetchMoviesPosters extends AsyncTask<String, Void, String[]> {
        private final String LOG_TAG = FetchMoviesPosters.class.getSimpleName();


        private String[] MoviesJasonPrase(String moviesPosterStr) throws JSONException {


            JSONObject moviesJson = new JSONObject(moviesPosterStr);
            JSONArray resultsArray = moviesJson.getJSONArray("results");
            movieId = new String[resultsArray.length()];
            movieTitle = new String[resultsArray.length()];
            movieReleaseDate = new String[resultsArray.length()];
            movieVoteAverage = new String[resultsArray.length()];
            movieOverview = new String[resultsArray.length()];
            moviePosterPath = new String[resultsArray.length()];


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

                JSONObject movie = resultsArray.getJSONObject(i);
                movieId[i] = movie.getString("id");
                movieTitle[i] = movie.getString("original_title");
                movieReleaseDate[i] = movie.getString("release_date");
                movieVoteAverage[i] = movie.getString("vote_average");
                movieOverview[i] = movie.getString("overview");
                moviePosterPath[i] = movie.getString("poster_path");



   //                    String resultStrs = moviesPosterStr + movieId ;

            }


            return moviePosterPath;

        }

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

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


            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String moviePostersJsonStr = null;


            try {

                final String FORECAST_BASE_URL =
                        "https://api.themoviedb.org/3/discover/movie?";
                final String SORT_OPTI = "sort_by";
                final String APPID_PARAM = "api_key";

                Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                        .appendQueryParameter(SORT_OPTI, params[0])
                        .appendQueryParameter(APPID_PARAM, BuildConfig.THE_MOVIE_DB)
                        .build();

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

                Log.v(LOG_TAG, "Built URI " + builtUri.toString());
                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuilder buffer = new StringBuilder();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line).append("\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                moviePostersJsonStr = buffer.toString();
                Log.v(LOG_TAG, "Data:" + moviePostersJsonStr);
            } catch (IOException e) {
                Log.e("PhotoGrid", "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("PhotoGrid", "Error closing stream", e);
                    }
                }

            }
            try {
                return MoviesJasonPrase(moviePostersJsonStr);
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] Strings) {
            if (Strings != null) {

                string1 = new String[Strings.length];
                for (int i = 0; i < Strings.length; i++) {
                    String[] getImage = Strings[i].split("-");
                    string1[i] = "http://image.tmdb.org/t/p/w185/" + getImage[0];
                }
                ImageAdapter imageAdapter = new ImageAdapter(getActivity(), string1);
                gridView.setAdapter(imageAdapter);

            }
        }
    }
}