How to transform the context of fragment into a LifecycleOwner? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to transform the context of fragment into a LifecycleOwner? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have the following scenario. I have an activity which holds a fragment. In this fragment I’m displaying some records from a back-end database. I’m also using an adapter that looks like this:

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);
        }
    }
}

In the onBindViewHolder I’m trying to check if a specific movie exist in Romm database but I get this error:

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

So how to transform the context of fragment into a LifecycleOwner so I can use it as in argument in my method?

Answer

android.content.Context does not implement android.arch.lifecycle.LifecycleOwner.

You’d have to pass an instance of AppCompatActivity, which implements android.arch.lifecycle.LifecycleOwner (or any other class which does that).

or cast (AppCompatActivity) context, when context is an instanceof AppCompatActivity. To get the Activity from the Context in a reliable manner, check https://stackoverflow.com/a/46205896/2413303

We are here to answer your question about How to transform the context of fragment into a LifecycleOwner? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji