Always Learner
Always Learner

Reputation: 3016

How to transform the context of fragment into a LifecycleOwner?

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?

Upvotes: 10

Views: 15591

Answers (2)

MDT
MDT

Reputation: 1695

Posting this for people figuring out the solution suggested above, below i have added a short hand extension version of this for kotlin android

private fun Context?.getLifeCycleOwner() : AppCompatActivity? = when {
    this is ContextWrapper -> if (this is AppCompatActivity) this else this.baseContext.getLifeCycleOwner()
    else -> null
}

Usage of above extension in a fragment would look like :

private var mainActivityContext: Context? = null //class level variable

//below statement called after context variable assigned / OnCreate
mainActivityContext?.getLifeCycleOwner()?.let { lifeCycleOwner ->
            YourViewModel.liveDataReturningMethod(text.toString())
                .observe(lifeCycleOwner , Observer { x ->
                    //your logic here...
                })
        }

Upvotes: 1

Martin Zeitler
Martin Zeitler

Reputation: 76779

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

Upvotes: 14

Related Questions