如何将片段的上下文转换为LifecycleOwner?

时间:2019-01-31 12:56:02

标签: java android android-room android-livedata

我有以下情况。我有一个包含片段的活动。在此片段中,我将显示来自后端数据库的一些记录。我还使用了一个看起来像这样的适配器:

public class MovieAdapter extends PagedListAdapter<Movie, MovieAdapter.MovieViewHolder> {
    private Context context;

    public MovieAdapter(Context context) {this.context = context;}

    @NonNull
    @Override
    public MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //Create the view
    }

    @Override
    public void onBindViewHolder(@NonNull final MovieViewHolder holder, int position) {
        Movie movie = getItem(position);
        String title = movie.title;
        holder.titleTextView.setText(title);

        MovieRepository movieRepository = new MovieRepository(context);
        LiveData<Movie> liveData = movieRepository.retrieveFavoriteMovie(movie.id);
        liveData.observe(context, m -> { //Error
            if(m != null) {
                boolean favorite = m.favorite;
                if(favorite) {
                    //Do something
                } else {
                    //Do something else
                }
            }
        });
    }

    class MovieViewHolder extends RecyclerView.ViewHolder {
        ImageView favoriteImageView;
        TextView titleTextView;

        MovieViewHolder(View itemView) {
            super(itemView);
            titleTextView = itemView.findViewById(R.id.title_text_view);                favoriteImageView = itemView.findViewById(R.id.favorite_image_view);
        }
    }
}

onBindViewHolder中,我试图检查Romm数据库中是否存在特定电影,但出现此错误:

Wrong 1st argument type. Found: 'android.content.Context', required: 'android.arch.lifecycle.LifecycleOwner'

那么如何将片段的上下文转换为LifecycleOwner,以便可以在方法中的参数中使用它?

1 个答案:

答案 0 :(得分:0)

android.content.Context未实现android.arch.lifecycle.LifecycleOwner

您必须传递一个AppCompatActivity实例,该实例实现android.arch.lifecycle.LifecycleOwner(或执行此操作的任何其他类)。

或在(AppCompatActivity) contextcontext的实例时强制转换AppCompatActivity