2

I am using an AsyncTask to connect to the following URL:

https://api.themoviedb.org/3/movie/upcoming?api_key=6572f232190d6b55ec917726dab87783

One of the values I am having trouble with is the genre_id. As it is a JSONArray I add the values to an ArrayList. I then later want to convert these values to the String correspondence which are found here:

http://api.themoviedb.org/3/genre/movie/list?api_key=6572f232190d6b55ec917726dab87783

// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre_ids");
ArrayList<Integer> genre = new ArrayList<Integer>();
for (int j = 0; j < genreArry.length(); j++) {

    genre.add(genreArry.optInt(j));

}

I'm just wondering what is the best way to do this? I am a displaying a ListView of all the information and for each row all the information is correct. I just need to convert the Genre id into the corresponding String. I have tried the code below but the TextView is always overwritten by the last value. Does anyone know of a better way to do this?

  private void getGenre(int genre) {
         for (int i = 0; i < genreList.size(); i++) {

             Log.d("THE", "THE GENRE ADAPTER RETRIEVED IS" + i + genreList.get(i).getId() + genreList.get(i).getName());

             if (genreList.get(i).getId() == genre) {

                 String name = genreList.get(i).getName();
                 mGenre.setText(name);
             }
         }

Solved.
I managed to get this working by doing a check in the onPostExecute of my AsyncTask

try {
    JSONObject json = new JSONObject(result);

    JSONArray movies = json.getJSONArray("results");
    for (int i = 0; i < movies.length(); i++) {

        JSONObject obj = movies.getJSONObject(i);

        //Create Movie Object
        Movie movie = new Movie();

        //get values from JSON
        movie.setTitle(obj.getString("original_title"));
        movie.setPopularity(obj.getString("popularity"));
        movie.setYear(obj.getString("release_date"));
        movie.setThumbnailUrl(obj.getString("poster_path"));
        movie.setOverView(obj.getString("overview"));

        // Genre is json array
        JSONArray genreArry = obj.getJSONArray("genre_ids");
        ArrayList<Integer> genre = new ArrayList<Integer>();
        ArrayList<String> genreName = new ArrayList<String>();
        for (int j = 0; j < genreArry.length(); j++) {

            genre.add(genreArry.optInt(j));

            for (int zz = 0; zz < myGenreList.size(); zz++) {

                if (myGenreList.get(zz).getId() == genre.get(j)) {

                    String name = myGenreList.get(zz).getName();
                    genreName.add(name);
                }
            }
        }

        movie.setGenre(genre);
        movie.setGenreName(genreName);
4
  • Not sure that you picked up the right collection try HashMap<Int, String> or SparseArray Commented Dec 15, 2015 at 17:08
  • The TextView is always overwritten and is the last value because the reference to mGenre at mGenre.setText(name); never changes. Commented Dec 15, 2015 at 17:17
  • Show us the logcat generated by the Log.d(...' inside the loop. Also, show the value of int genre parameter in that log. Commented Dec 15, 2015 at 17:27
  • BTW.. why do you name a method called "getSomething" that returns "void"? I don't get it... getSomething should return Something (or null), agree? Commented Dec 15, 2015 at 17:33

1 Answer 1

1

I prefer Volley instead of AsyncTask for simplicity, but you are more than welcome to use either. Note, AsyncTask will require quite a bit more work.

From what I have provided here, you should be able to get my screenshot after building the ListView item XML.

I loosely followed this guide to get started quickly.

Screenshot

Screenshot


Movie.java - Model Object

public class Movie {

    private int id;
    private String title;
    private List<String> genres;

    public Movie() {
        this(-1, null);
    }

    public Movie(int id, String title) {
        this.id = id;
        this.title = title;
        this.genres = new ArrayList<String>();
    }

    public void addGenre(String s) {
        this.genres.add(s);
    }

    public String getTitle() {
        return title;
    }

    public List<String> getGenres() {
        return genres;
    }
}

MovieAdapter.java - ListView adapter

public class MovieAdapter extends ArrayAdapter<Movie> {

    private final int layoutId;

    public MovieAdapter(Context context, List<Movie> objects) {
        super(context, 0, objects);
        layoutId = R.layout.item_movie;
    }

    private static class ViewHolder {
        TextView title;
        TextView genres;
    }

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

        Movie movie = getItem(position);

        ViewHolder viewHolder; // view lookup cache stored in tag
        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(layoutId, parent, false);
            viewHolder.title = (TextView) convertView.findViewById(R.id.movie_title);
            viewHolder.genres = (TextView) convertView.findViewById(R.id.movie_genres);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        // Populate the data into the template view using the data object
        viewHolder.title.setText(movie.getTitle());
        viewHolder.genres.setText(String.valueOf(movie.getGenres()));
        // Return the completed view to render on screen
        return convertView;
    }
}

MainActivity.java

public class MainActivity extends Activity {

    private static final String GENRES_URL = "http://api.themoviedb.org/3/genre/movie/list?api_key=6572f232190d6b55ec917726dab87783";
    private static final String MOVIES_URL = "https://api.themoviedb.org/3/movie/upcoming?api_key=6572f232190d6b55ec917726dab87783";

    private HashMap<Integer, String> genreMap = new HashMap<Integer, String>();

    private List<Movie> movies = new ArrayList<Movie>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView lv = (ListView) findViewById(R.id.listView);
        final MovieAdapter movieAdapter = new MovieAdapter(this, movies);
        lv.setAdapter(movieAdapter);

        // Build the genres map
        JsonObjectRequest request1 = new JsonObjectRequest(GENRES_URL, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray genres = response.getJSONArray("genres");

                            for (int i = 0; i < genres.length(); i++) {
                                JSONObject genre = genres.getJSONObject(i);
                                int id = genre.getInt("id");
                                String name = genre.getString("name");
                                genreMap.put(id, name);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },

                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Network error", error.getMessage());
                    }
                }
        );
        VolleyApplication.getInstance().getRequestQueue().add(request1);

        JsonObjectRequest request2 = new JsonObjectRequest(MOVIES_URL, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        movieAdapter.clear();
                        try {
                            JSONArray results = response.getJSONArray("results");

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

                                JSONObject result = results.getJSONObject(i);

                                int movieId = result.getInt("id");
                                String title = result.getString("original_title");
                                Movie movie = new Movie(movieId, title);

                                JSONArray genreIds = result.getJSONArray("genre_ids");
                                for (int j = 0; j < genreIds.length(); j++) {
                                    int id = genreIds.getInt(j);
                                    String genre = genreMap.get(id);
                                    movie.addGenre(genre);
                                }

                                movieAdapter.add(movie);
                            }

                        } catch (JSONException e) {
                            Log.e("JSONException", e.getMessage());
                        }
                    }
                },

                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Network error", error.getMessage());
                    }
                }
        );
        VolleyApplication.getInstance().getRequestQueue().add(request2);


    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks If you see my edit above you can see my answer for getting it working. Is there any real advantage of using Volley over AysncTask? Is it much faster?
I'm not sure about faster, I just prefer it because you can do simple network calls in the activity and the JsonObjectRequest is already built in, so you don't need to worry about parsing a string. Basically, just removes alot of boilerplate from AsyncTask network calls. Also, you don't need to worry about callbacks like onPostExecute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.