我想创建电影应用程序,它在回收器视图中显示电影列表,我使用改造库来调用 api 电影数据库,在 MainActivity 中我使用 try and catch 如果请求为空打印“请首先从 themoviedb.org 获取 API 密钥",并在 onFailure() 方法打印错误消息,当我运行我的应用程序时,什么都没有出现!在此处输入图像描述
我的活动主要
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MoviesAdapter adapter;
private List<Movie> movieList;
ProgressDialog pd;
private SwipeRefreshLayout swipeContainer;
public static final String LOG_TAG = MoviesAdapter.class.getName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeContainer = (SwipeRefreshLayout) findViewById(R.id.main_content);
swipeContainer.setColorSchemeResources(android.R.color.holo_orange_dark);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
initViews();
Toast.makeText(MainActivity.this, "Movies Refreshed", Toast.LENGTH_SHORT).show();
}
});
}
public Activity getActivity() {
Context context = this;
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
private void initViews() {
pd = new ProgressDialog(this);
pd.setMessage("Feitching Movies..");
pd.setCancelable(false);
pd.show();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
movieList = new ArrayList<>();
adapter = new MoviesAdapter(this, movieList);
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
}
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void loadJSON() {
try {
if (BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please obtain API Key firstly from themoviedb.org", Toast.LENGTH_SHORT).show();
pd.dismiss();
return;
}
Client Client = new Client();
Service apiService =
Client.getClient().create(Service.class);
Call<MoviesResponse> call = apiService.getPopularMovies(BuildConfig.THE_MOVIE_DB_API_TOKEN);
call.enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {
List<Movie> movies = response.body().getResults();
Collections.sort(movies, Movie.BY_NAME_ALPHABETICAL);
recyclerView.setAdapter(new MoviesAdapter(getApplicationContext(), movies));
recyclerView.smoothScrollToPosition(0);
if (swipeContainer.isRefreshing()){
swipeContainer.setRefreshing(false);
}
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
Toast.makeText(MainActivity.this, "Error Fetching Data!", Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e){
Log.d("Error", e.getMessage());
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.menu_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
我的 detailActivity 类
public class DetailActivity extends AppCompatActivity {
TextView nameOfMovie, plotSynopsis, userRating, releaseDate;
ImageView imageView;
Movie movie;
String thumbnail, movieName, synopsis, rating, dateOfRelease;
int movie_id;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detial);
initCollapsingToolbar();
imageView = (ImageView) findViewById(R.id.thumbnail_image_header);
nameOfMovie = (TextView) findViewById(R.id.title);
plotSynopsis = (TextView) findViewById(R.id.plotsynopsis);
userRating = (TextView) findViewById(R.id.userrating);
releaseDate = (TextView) findViewById(R.id.releasedate);
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity.hasExtra("Original_title")) {
String thumbnail = getIntent().getExtras().getString("poster_path");
String movieName=getIntent().getExtras().getString("original_title");
String synopsis =getIntent().getExtras().getString("overview");
String rating =getIntent().getExtras().getString("realese_date");
String poster = "https://image.tmdb.org/t/p/w500" + thumbnail;
Glide.with(this)
.load(poster)
.placeholder(R.drawable.load)
.into(imageView);
nameOfMovie.setText(movieName);
plotSynopsis.setText(synopsis);
userRating.setText(rating);
releaseDate.setText(dateOfRelease);
} else {
Toast.makeText(this, "No API Data", Toast.LENGTH_SHORT).show();
}
}
private void initCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbarLayout =
(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.setExpanded(true);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbarLayout.setTitle(getString(R.string.movie_details));
isShow = true;
} else if (isShow) {
collapsingToolbarLayout.setTitle(" ");
isShow = false;
}
}
});
}
}
电影课
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Created by delaroy on 5/18/17.
*/
public class Movie implements Parcelable {
@SerializedName("poster_path")
private String posterPath;
@SerializedName("adult")
private boolean adult;
@SerializedName("overview")
private String overview;
@SerializedName("release_date")
private String releaseDate;
@SerializedName("genre_ids")
private List<Integer> genreIds = new ArrayList<Integer>();
@SerializedName("id")
private Integer id;
@SerializedName("original_title")
private String originalTitle;
@SerializedName("original_language")
private String originalLanguage;
@SerializedName("title")
private String title;
@SerializedName("backdrop_path")
private String backdropPath;
@SerializedName("popularity")
private Double popularity;
@SerializedName("vote_count")
private Integer voteCount;
@SerializedName("video")
private Boolean video;
@SerializedName("vote_average")
private Double voteAverage;
public Movie(String posterPath, boolean adult, String overview, String releaseDate, List<Integer> genreIds, Integer id,
String originalTitle, String originalLanguage, String title, String backdropPath, Double popularity,
Integer voteCount, Boolean video, Double voteAverage) {
this.posterPath = posterPath;
this.adult = adult;
this.overview = overview;
this.releaseDate = releaseDate;
this.genreIds = genreIds;
this.id = id;
this.originalTitle = originalTitle;
this.originalLanguage = originalLanguage;
this.title = title;
this.backdropPath = backdropPath;
this.popularity = popularity;
this.voteCount = voteCount;
this.video = video;
this.voteAverage = voteAverage;
}
public Movie(){
}
public static final Comparator<Movie> BY_NAME_ALPHABETICAL = new Comparator<Movie>() {
@Override
public int compare(Movie movie, Movie t1) {
return movie.originalTitle.compareTo(t1.originalTitle);
}
};
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public List<Integer> getGenreIds() {
return genreIds;
}
public void setGenreIds(List<Integer> genreIds) {
this.genreIds = genreIds;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public Double getPopularity() {
return popularity;
}
public void setPopularity(Double popularity) {
this.popularity = popularity;
}
public Integer getVoteCount() {
return voteCount;
}
public void setVoteCount(Integer voteCount) {
this.voteCount = voteCount;
}
public Boolean getVideo() {
return video;
}
public void setVideo(Boolean video) {
this.video = video;
}
public Double getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(Double voteAverage) {
this.voteAverage = voteAverage;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.posterPath);
dest.writeByte(this.adult ? (byte) 1 : (byte) 0);
dest.writeString(this.overview);
dest.writeString(this.releaseDate);
dest.writeList(this.genreIds);
dest.writeValue(this.id);
dest.writeString(this.originalTitle);
dest.writeString(this.originalLanguage);
dest.writeString(this.title);
dest.writeString(this.backdropPath);
dest.writeValue(this.popularity);
dest.writeValue(this.voteCount);
dest.writeValue(this.video);
dest.writeValue(this.voteAverage);
}
protected Movie(Parcel in) {
this.posterPath = in.readString();
this.adult = in.readByte() != 0;
this.overview = in.readString();
this.releaseDate = in.readString();
this.genreIds = new ArrayList<Integer>();
in.readList(this.genreIds, Integer.class.getClassLoader());
this.id = (Integer) in.readValue(Integer.class.getClassLoader());
this.originalTitle = in.readString();
this.originalLanguage = in.readString();
this.title = in.readString();
this.backdropPath = in.readString();
this.popularity = (Double) in.readValue(Double.class.getClassLoader());
this.voteCount = (Integer) in.readValue(Integer.class.getClassLoader());
this.video = (Boolean) in.readValue(Boolean.class.getClassLoader());
this.voteAverage = (Double) in.readValue(Double.class.getClassLoader());
}
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
@Override
public Movie createFromParcel(Parcel source) {
return new Movie(source);
}
@Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
界面 :
public interface Service {
@GET("movie/popular")
Call<MoviesResponse> getPopularMovies(@Query("api_key") String apiKey);
@GET("movie/top_rated")
Call<MoviesResponse> getTopRatedMovies(@Query("api_key") String apiKey);
}