Search code examples
androidpopularity

Udacity Popular movie Stage 1 Issue


My app is supposed to fetch popular movies photos from TheMovieDB API into a GridView.

I have built all the app components and what's left is how to load the photos into the adapter array when it lands on the phone, How?!

Below is my fragment code.

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);

        }
    }
    }
}

This is part of what I am getting from the API I used a JSONformatter to make it clearer:

{  
  "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
  },

Solution

  • Below is the code after a lot of editing now it is working, posters are displayed

    finally.

    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);
    
                }
            }
        }
    }