我在MVVM中给出了第一步,我有一个使用改装的imbd应用程序。此时此刻,我有一个动态URL,通过传递不同的电影id来更改电影列表
@GET("3/movie/{movie_id}}/similar?api_key="+api_key+"&language=en-US&page=1")
Call<Similar> getAllSimilarMovies(@Path("movie_id") int movieId);
我有一个存储库,我试图在其中获取Intent值,但.getIntent不起作用,Intent在recyclerview中通过点击的电影的ID
public class DetailsMovieRepository {
private List<ResultSimilar> similarMoviesList;
private MutableLiveData<List<ResultSimilar>> mutableLiveData = new MutableLiveData<>();
public MutableLiveData<List<ResultSimilar>> getSimilarMutableliveData() {
MovieDataService movieDataService = RetrofitInstance.getRetrofitInstance();
Intent intent = getIntent(); // DONT WORK!
int movieId = intent.getIntExtra("movie_id",0);
Call<Similar> call = movieDataService.getAllSimilarMovies(movieId);
call.enqueue(new Callback<Similar>() {
@Override
public void onResponse(Call<Similar> call, Response<Similar> response) {
Similar similar = response.body();
if (similar != null && similar.getResults() != null) {
similarMoviesList = similar.getResults();
mutableLiveData.setValue(similarMoviesList);
}
}
@Override
public void onFailure(Call<Similar> call, Throwable t) {
Log.e("onFailed", " ******" + t.getMessage() + "*******");
}
});
return mutableLiveData;
}
}
问题是,我如何从Intent中获得值,保存为var并将传递到这里
Call<Similar> call = movieDataService.getAllSimilarMovies(---MY INTENT VALUE---);
适配器中的启动意图
private SimilarViewHolder(@NonNull View itemView) {
super(itemView);
movieNameTv = itemView.findViewById(R.id.name_movie_tv);
movieRatingTv = itemView.findViewById(R.id.rating_movie_tv);
moviePosterIV = itemView.findViewById(R.id.movie_poster_iv);
movieDateTv = itemView.findViewById(R.id.date_movie_tv);
movieVotesTv = itemView.findViewById(R.id.votes_movie_tv);
movieOriginalTitleTv = itemView.findViewById(R.id.original_title_tv);
movieLanguageTv = itemView.findViewById(R.id.language_movie_tv);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
ResultSimilar selectedMovie = similarMoviesList.get(position);
Intent intent = new Intent(context, DetailsActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("movie_id",selectedMovie.getId());
intent.putExtras(bundle);
context.startActivity(intent);
Log.e("ddddd" , "***" + selectedMovie.getId());
}});
}
}
数据服务
public interface MovieDataService {
String api_key = "5bbf68dcf3b4ad3875ef7b2ed5ddfe1a";
@GET("3/movie/now_playing?api_key="+api_key+"&language=en-US&page=1")
Call<Movies> getAllMovies();
@GET("3/movie/{movie_id}}?api_key="+api_key+"&language=en-US")
Call<MovieResponse> getMovieDetails(@Path("movie_id") int movieId) ;
@GET("3/movie/{movie_id}}/similar?api_key="+api_key+"&language=en-US&page=1")
Call<Similar> getAllSimilarMovies(@Path("movie_id") int movieId);
}
谢谢!
如果您想从Intent
获取数据,那么您应该在Activity
类中进行,然后您可以从构造函数(例如detailsMovieRepository(int id);
(将其传递给存储库