Я хочу показать жанровые названия каждого фильма в каждой детали деятельности. Я получил genre_ids, прикрепленный к фильму с запросом, и список жанров с идентификаторами и именем с другим запросом.
Например, мне нужно «Действие, Драма, Фантастика» вместо «28, 18, 878»
Скриншот
Я на самом деле не профессионал в Java / Android, поэтому я не знаю, где в коде я могу сравнить два идентификатора, чтобы получить имя и отобразить его.
Мой код:
MainActivity.java:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private RecyclerView moviesView;
private MoviesAdapter adapter;
private GridLayoutManager gridLayoutManager;
private List<Movie> moviesList;
private int currentPage = 1;
private boolean movieSearch = false;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
moviesView = (RecyclerView) findViewById(R.id.movies_list);
moviesList = new ArrayList<>();
load_movies(currentPage);
gridLayoutManager = new GridLayoutManager(this,2);
moviesView.setLayoutManager(gridLayoutManager);
adapter = new MoviesAdapter(this, moviesList);
moviesView.setAdapter(adapter);
}
public String getLocale() {
String countryCode = Locale.getDefault().getCountry();
String languageCode = Locale.getDefault().getLanguage();
String localeCode = languageCode + "-" + countryCode;
return localeCode;
}
private void load_movies(int id) {
AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... integers) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(BASE_URL + "/discover/movie?api_key=" + API_KEY + "&language=" + getLocale() + "&sort_by=popularity.desc&include_adult=false&include_video=false&page=" + integers[0])
.build();
try {
Response response = client.newCall(request).execute();
JSONObject root = new JSONObject(response.body().string());
JSONArray array = root.getJSONArray("results");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Movie data = new Movie();
if (object != null) {
JSONArray genresids = object.optJSONArray("genre_ids");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genresids.length(); j++) {
genre.add((String) genresids.getString(j));
}
data.setGenres(genre);
}
data.setTitle(object.getString("title"));
data.setPosterPath(object.getString("poster_path"));
data.setBackdropPath(object.getString("backdrop_path"));
data.setReleaseDate(object.getString("release_date"));
data.setOverview(object.getString("overview"));
data.setTMDBRating(object.getDouble("vote_average"));
moviesList.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of content");
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(id);
}
}
MovieDetailActivity.java:
public class MovieDetailActivity extends AppCompatActivity {
private ImageView image;
private TextView date,synopsys,title;
private static final String TAG = "Movidetail";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_movie_detail);
load_genres();
final FloatingActionButton seen = findViewById(R.id.buttonseen);
final FloatingActionButton tosee =findViewById(R.id.buttontosee);
final Movie details = (Movie) getIntent().getExtras().getSerializable("MOVIE_DETAILS");
image = findViewById(R.id.poster);
title = findViewById(R.id.title);
date = findViewById(R.id.date);
RatingBar rating = (RatingBar) findViewById(R.id.ratingBar);
synopsys = findViewById(R.id.synopsys);
if (details != null){
Glide.with(this).load("https://image.tmdb.org/t/p/w300"+details.getBackdropPath()).into(image);
// genre
String genreStr = "";
for (String str : details.getGenres()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ? genreStr.substring(0,
genreStr.length() - 2) : genreStr;
titre.setText(genreStr);
date.setText(details.getReleaseDate());
synopsys.setText(details.getOverview());
double d = details.getTMDBRating();
float f = (float) d;
rating.setRating(f/2);
}
}
private void load_genres() {
AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... integers) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.themoviedb.org/3/genre/movie/list?api_key=XXXX&language=fr-FR")
.build();
try {
Response response = client.newCall(request).execute();
JSONObject root = new JSONObject(response.body().string());
JSONArray array = root.getJSONArray("genres");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Genre data = new Genre();
data.setId(object.getInt("id"));
data.setName(object.getString("name"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of content");
}
return null;
}
};
task.execute();
}
}