如何从android中的tmdb api使用其类型id获取电影的类型

时间:2015-08-31 13:04:28

标签: android themoviedb-api

我想在android中使用tmdb api显示电影的类型,但事情是在tmdb api中首先我们必须找出类型id然后我们可以显示类型名称&我能够显示流派id但不能显示流派名称。请帮帮我

这是MovieFragment.java文件

公共类MovieFragment扩展Fragment {

public static final String LOG_TAG = MovieFragment.class.getSimpleName();
public static final int MOVIE_LOADER = 0;
private ImageAdapter imageAdapter;


public MovieFragment() {

}

@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 menuInflater) {
    menuInflater.inflate(R.menu.menu_movie_list, menu);
    super.onCreateOptionsMenu(menu, menuInflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_refresh) {
        updateMovie();
        return true;
    }
    return super.onOptionsItemSelected(item);
}


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

    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    return rootView;
}

private void updateMovie() {
    FetchMoviesTask moviesTask = new FetchMoviesTask(getActivity());
    moviesTask.execute();
}

public void onStart() {
    super.onStart();
    updateMovie();
}

public class FetchMoviesTask extends AsyncTask<Void, Void, JSONObject[]> {

    private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
    private final String MESSAGE = "MovieDetails";
    private final String GENRE_MESSAGE = "GenreDetails";
    private final Context mContext;

    public FetchMoviesTask(Context context) {
        mContext = context;
    }

    private boolean DEBUG = true;
    private ProgressDialog progress;

    protected void onPreExecute() {
        progress=new ProgressDialog(getActivity());
        progress.show();
        super.onPreExecute();
    }

    @Override
    protected JSONObject[] doInBackground(Void... params) {
        // URL for calling the API is needed
        final String MOVIE_BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
        final String MOVIE_BASE_GENRE_URL = "http://api.themoviedb.org/3/genre/movie/list?";
        //final String API_KEY = getString(R.string.API_KEY);

        final String API_KEY = getString(R.string.API_KEY);
        final String OWM_APIKEY = "api_key";
        final String OWM_SORT_BY = "sort_by";

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String sort_by = prefs.getString(getString(R.string.pref_movie_key), getString(R.string.pref_sort_default_value));

        //Built the uri
        Uri builtUri = Uri.parse(MOVIE_BASE_URL).buildUpon()
                .appendQueryParameter(OWM_APIKEY, API_KEY)
                .appendQueryParameter(OWM_SORT_BY, sort_by)
                .build();

        //Built the genre url
        Uri builtGenreUri = Uri.parse(MOVIE_BASE_GENRE_URL).buildUpon()
                .appendQueryParameter(OWM_APIKEY, API_KEY)
                .build();

        String url = builtUri.toString();
        String genreUrl = builtGenreUri.toString();

        JSONParser jParser = new JSONParser();
        JSONObject[] json = new JSONObject[2];

        json[0] = jParser.getJSONFromUrl(url);
        json[1] = jParser.getJSONFromUrl(genreUrl);
        //JSONObject json = jParser.getJSONFromUrl(url);

        return json; //the return value will be used by onPostExecute to update UI

    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(final JSONObject[] json) {

        progress.dismiss();

        //JSON objects that need to be extracted
        final String OWM_RESULT = "results";
        final String OWM_ID = "id";
        final String OWM_TITLE = "original_title";
        final String OWM_SYNOPSIS = "overview";
        final String OWM_POSTER_PATH = "poster_path";
        final String OWM_RATING = "vote_average";
        final String OWM_RELEASE_DATE = "release_date";
        final String OWM_POPULARITY = "popularity";
        final String OWM_GENRE = "genre_ids";
        final String OWM_GENRES = "genres";


        List<String> poster_paths = new ArrayList<String>();
        List<String> genreIds = new ArrayList<String>();
        List<String> genreNames = new ArrayList<String>();

        JSONArray movies_list_array;
        JSONArray genres_list_array;

        if(json != null) {
            try {

                movies_list_array = json[0].getJSONArray(OWM_RESULT);
                genres_list_array = json[1].getJSONArray(OWM_GENRES);

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

                    JSONObject movie = movies_list_array.getJSONObject(i);
                    poster_paths.add(movie.getString(OWM_POSTER_PATH));

                }

                for (int j = 0; j < genres_list_array.length(); j++) {

                    JSONObject genre = genres_list_array.getJSONObject(j);
                    genreIds.add(genre.getString(OWM_ID));
                    genreNames.add(genre.getString("name"));

                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error parsing JSON:", e);
            }


            GridView gridview = (GridView) getActivity().findViewById(R.id.movies_list_grid);
            gridview.setAdapter(new ImageAdapter(getActivity(), poster_paths));

            gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                    try {
                        JSONObject movieDetails = json[0].getJSONArray(OWM_RESULT).getJSONObject(position);
                        JSONObject genreDetails = json[1].getJSONArray(OWM_GENRES).getJSONObject(position);
                        Intent intent = new Intent(getActivity(), DetailActivity.class)
                                .putExtra(MESSAGE, movieDetails.toString())
                                .putExtra(GENRE_MESSAGE, genreDetails.toString());
                        startActivity(intent);

                    } catch (JSONException e) {
                        Log.e(LOG_TAG, "Error parsing json", e);
                    }

                }
            });

        } else {

            try {
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();

                alertDialog.setTitle("Info");
                alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
                alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {


                    }
                });

                alertDialog.show();
            }
            catch(Exception e)
            {
                Log.d(LOG_TAG, "Show Dialog: "+e.getMessage());
            }
        }
    }
}

}

这是DetailFragment文件

公共类DetailFragment扩展了Fragment {

private static final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final int DETAIL_LOADER = 0;
private static final String MESSAGE = "MovieDetails";
private static final String GENRE_MESSAGE = "GenreDetails";
static final String DETAIL_URI = "URI";
private Uri mUri;

//SharedPreference sharedPreference;

final String OWM_TITLE = "original_title";
final String OWM_POSTER = "poster_path";
final String OWM_RELEASE_DATE = "release_date";
final String OWM_SYNOPSIS = "overview";
final String OWM_RATING = "vote_average";
final String OWM_ID = "id";
final String OWM_GENRE_ID = "genre_ids";
final String OWM_GENRES = "genres";
//final String API_KEY = getString(R.string.API_KEY);

public DetailFragment() {

}

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

    Intent intent = getActivity().getIntent();
    String jsonString = intent.getStringExtra(MESSAGE);
    String genreString = intent.getStringExtra(GENRE_MESSAGE);

    try {

        final JSONObject jObj = new JSONObject(jsonString);
        final JSONObject genreObj = new JSONObject(genreString);

        TextView movieTitle = (TextView) rootView.findViewById(R.id.movie_title);
        movieTitle.setText(jObj.getString(OWM_TITLE));

        ImageView moviePoster = (ImageView) rootView.findViewById(R.id.movie_poster);
        String basepath = "http://image.tmdb.org/t/p/w185/";
        String relativePath = jObj.getString(OWM_POSTER);

        Glide.with(getActivity()).load(basepath+relativePath).into(moviePoster);

        TextView movieRating = (TextView) rootView.findViewById(R.id.movie_rating);
        Float rating = Float.valueOf(jObj.getString(OWM_RATING));
        movieRating.setText("Rating: " + rating + "/10");

        RatingBar ratingBar = (RatingBar) rootView.findViewById(R.id.rating_bar);
        ratingBar.setRating(rating);

        TextView movieSynopsis = (TextView) rootView.findViewById(R.id.movie_synopsis);
        movieSynopsis.setText(jObj.getString(OWM_SYNOPSIS));

        TextView movieReleaseDate = (TextView) rootView.findViewById(R.id.movie_release_date);
        movieReleaseDate.setText(jObj.getString(OWM_RELEASE_DATE));

        TextView movieGenres = (TextView) rootView.findViewById(R.id.genres);

        JSONArray jArray = jObj.getJSONArray(OWM_GENRE_ID);
        StringBuilder builder = new StringBuilder();

        //List<String> returnList = new ArrayList<String>();

        for (int i = 0; i < jArray.length(); i++) {
            String val = jArray.getString(i);
            builder.append(val + " ");
            //returnList.add(val);
            movieGenres.setText(builder.toString());
        }

        String date = (String) movieReleaseDate.getText().toString();
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date convertedDate = formatter.parse(date);
            SimpleDateFormat postFormatter = new SimpleDateFormat("yyyy MMM dd");
            String finalDate = postFormatter.format(convertedDate);
            movieReleaseDate.setText(finalDate);
            //String finalDate = formatter("YYYY MMM DD").format(convertedDate);
        } catch(ParseException e) {
            Log.e(LOG_TAG, "Error Parsing Date: ", e);
        }


    } catch (JSONException e) {
        Log.e(LOG_TAG, "Error Parsing JSON: ", e);
    }

    return rootView;
}

}

那么,当我遇到困难时如何解决这个问题&amp;无法找到任何方法。那么,当我使用这个API时,如何使用tmdb api获取类型名称。请帮忙

2 个答案:

答案 0 :(得分:0)

您必须将您的流派_id 与您可以从此处获取的流派列表进行映射:https://developers.themoviedb.org/3/genres/get-movie-list。我希望我能帮助你:) (data["results"][0]["genre_ids"] 是我在这个例子中的流派列表) 这是我的代码:

    const genresRes = await fetch("https://api.themoviedb.org/3/genre/" + data["results"][0]["media_type"] + "/list?api_key=de51817441f3aca4f2ec89ee99f6c68c&language=en-US");
    const genresData = await genresRes.json();
    let genresThing = genresData["genres"]
    let genresHash = {};
    for (let i in genresThing){
        genresHash[genresThing[i]["id"]] = genresThing[i]["name"]
    }
    let genres = ""
    for (let i in data["results"][0]["genre_ids"]){
        genres += genresHash[data["results"][0]["genre_ids"][i]] + ", ";
    }
    this.dataNow.genres = genres
    console.log(this.dataNow.genres)

答案 1 :(得分:0)

您可以使用此 API 获取电影的更多信息,使用电影 ID。 https://developers.themoviedb.org/3/movies/get-movie-details 在这里您可以获得流派 ID 和流派名称的列表。 我希望我有帮助:)