getitemcount()在recyclelerview中使用movie api返回null

时间:2018-05-02 17:32:15

标签: android android-recyclerview recycler-adapter

getitemcount()null适配器中返回RecyclerView。当我运行我的应用程序时,它崩溃并且错误消息是getitemcount()中的电影项目大小返回null。

  

以下是相关代码:

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder>
{

   private Context context;
   private List<Movie> movieList;

    public MoviesAdapter(Context context, List<Movie> movieList) {
        this.context = context;
        this.movieList = movieList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_card,parent,false);
        return new  MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        holder.title.setText(movieList.get(position).getOriginal_title());
        String vote = Double.toString(movieList.get(position).getVoteAverage());
        holder.userrating.setText(vote);
        Glide.with(context).load(movieList.get(position).getPosterpath()).placeholder(R.drawable.loading).into(holder.imageView);

    }

    @Override
    public int getItemCount() {
        return movieList.size();
    }

    public  class MyViewHolder extends RecyclerView.ViewHolder
    {
        private TextView title,userrating;
        private ImageView imageView;

        public MyViewHolder(final View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.movietitle);
            userrating = (TextView) itemView.findViewById(R.id.userrating);
            imageView = (ImageView) itemView.findViewById(R.id.thumbnail);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int pos = getAdapterPosition();
                    if (pos != RecyclerView.NO_POSITION)
                    {
                        Movie clickedDataItem =  movieList.get(pos);
                        Intent intent = new Intent(context, DetailActivity.class);
                        intent.putExtra("original_title" , movieList.get(pos).getOriginal_title());
                        intent.putExtra("poster",movieList.get(pos).getPosterpath());
                        intent.putExtra("overview",movieList.get(pos).getOverview());
                        intent.putExtra("vot_average",movieList.get(pos).getVote_count());
                        intent.putExtra("release_date",movieList.get(pos).getRelease_data());
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                        Toast.makeText(view.getContext(),"you clicked "+clickedDataItem.getOriginal_title(),Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    }
}

public interface Service {

    @GET("/3/movie/popular")
    Call<MoviesResponse> getPopularMovies (@Query("api_key") String apikey);
}

public class MoviesResponse {

    private int page;
    private List <Movie> result;
    private int totalresult;
    private int totalpage;

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public List<Movie> getResult() {
        return result;
    }

    public void setResult(List<Movie> result) {
        this.result = result;
    }

    public int getTotalresult() {
        return totalresult;
    }

    public void setTotalresult(int totalresult) {
        this.totalresult = totalresult;
    }

    public int getTotalpage() {
        return totalpage;
    }

    public void setTotalpage(int totalpage) {
        this.totalpage = totalpage;
    }
}

public class Movie {

    private String posterpath;
    private boolean adult;
    private String overview;
    private String release_data;
    private List<Integer> genre_ids = new  ArrayList<Integer>();
    private int id;
    private String original_title;
    private String original_language;
    private String title;
    private String backdroppath;
    private Double popularity;
    private int vote_count;
    private boolean video;
    private Double voteAverage;

    public Movie(String posterpath, boolean adult, String overview, String release_data, List<Integer> genre_ids, int id, String original_title, String original_language, String title, String backdroppath, Double popularity, int vote_count, boolean video, Double voteAverage) {
        this.posterpath = posterpath;
        this.adult = adult;
        this.overview = overview;
        this.release_data = release_data;
        this.genre_ids = genre_ids;
        this.id = id;
        this.original_title = original_title;
        this.original_language = original_language;
        this.title = title;
        this.backdroppath = backdroppath;
        this.popularity = popularity;
        this.vote_count = vote_count;
        this.video = video;
        this.voteAverage = voteAverage;
    }

    String baseImageUrl = "https://image.tmdb.org/t/p/w500";

    public String getPosterpath() {
        return "https://image.tmdb.org/t/p/w500" + 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 getRelease_data() {
        return release_data;
    }

    public void setRelease_data(String release_data) {
        this.release_data = release_data;
    }

    public List<Integer> getGenre_ids() {
        return genre_ids;
    }

    public void setGenre_ids(List<Integer> genre_ids) {
        this.genre_ids = genre_ids;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getOriginal_title() {
        return original_title;
    }

    public void setOriginal_title(String original_title) {
        this.original_title = original_title;
    }

    public String getOriginal_language() {
        return original_language;
    }

    public void setOriginal_language(String original_language) {
        this.original_language = original_language;
    }

    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 int getVote_count() {
        return vote_count;
    }

    public void setVote_count(int vote_count) {
        this.vote_count = vote_count;
    }

    public boolean isVideo() {
        return video;
    }

    public void setVideo(boolean video) {
        this.video = video;
    }

    public Double getVoteAverage() {
        return voteAverage;
    }

    public void setVoteAverage(Double voteAverage) {
        this.voteAverage = voteAverage;
    }

    public String getBaseImageUrl() {
        return baseImageUrl;
    }

    public void setBaseImageUrl(String baseImageUrl) {
        this.baseImageUrl = baseImageUrl;
    }
}

public class Client {

    public static final String BASE_URL = "https://api.themoviedb.org";
    public static final String API_KEY = "5c723cbb6a71ce839dc704a80febe3fb";
    public static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
        }

        return retrofit;
    }

}

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private MoviesAdapter adapter;
    private List<Movie> movieList;
    ProgressDialog pd;
    private TextView textView;
    private SwipeRefreshLayout swipecontainer;
    public static final String LOG_TAG = MoviesAdapter.class.getName();

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

        initview();

        swipecontainer = (SwipeRefreshLayout) findViewById(R.id.main_content);
        swipecontainer.setColorSchemeColors(android.R.color.holo_orange_dark);
        swipecontainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initview();

                Toast.makeText(MainActivity.this,"Movies Refreshed",Toast.LENGTH_LONG).show();
            }
        });
    }

    public Activity getActivity ()
    {
        Context context =this;
        while (context instanceof ContextWrapper)
        {
            return (Activity) context;

        }
        context =((ContextWrapper) context).getBaseContext();
        return null;
    }

    private void initview() {

        pd = new  ProgressDialog(this);
        pd.setMessage("Fetching  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();

        loadjson();
    }

    private void loadjson() {


        try {
            if(BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty())
            {
                Toast.makeText(getApplicationContext(),"please obtain API key",Toast.LENGTH_LONG).show();
                return;
            }

            Client client= new Client();

            Service apiservice = Client.getClient().create(Service.class);

            Call<MoviesResponse> call = apiservice.getPopularMovies("5c723cbb6a71ce839dc704a80febe3fb");

            call.enqueue(new Callback<MoviesResponse>() {
                @Override
                public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {


                      List<Movie> movies = response.body().getResult();


                        recyclerView.setAdapter(new MoviesAdapter(getApplicationContext(),response.body().getResult()));
                        recyclerView.smoothScrollToPosition(0);
                        if (swipecontainer.isRefreshing()) {
                            swipecontainer.setRefreshing(false);
                        }
                        pd.dismiss();
                }

                @Override
                public void onFailure(retrofit2.Call<MoviesResponse> call, Throwable t) {
                    Log.d("Error" ,t.getMessage());
                    Toast.makeText(MainActivity.this,"Error Fetching Data! " ,Toast.LENGTH_LONG).show();
                }
            });

        }
        catch (Exception e)
        {
            Log.d("Error" ,e.getMessage());
            Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).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_setting :
            return true;

            default:return super.onOptionsItemSelected(item);
        }
    }
}

0 个答案:

没有答案