Home > Blockchain >  How to use context in a RecyclerView adapter for SharedPreferences?
How to use context in a RecyclerView adapter for SharedPreferences?

Time:01-28

I have a RecyclerView adapter for displaying a list of movies. I need to use the context to initialize the genrePreferences variable in my adapter. Where is the appropriate place in the adapter's lifecycle to initialize this variable?

class MovieAdapter(private val movieList: ArrayList<Movie>) :
RecyclerView.Adapter<MovieAdapter.MovieViewHolder>() {

private val BASE_POSTER_PATH = "https://image.tmdb.org/t/p/w342"
lateinit var genrePreferences: GenrePreferences
lateinit var genres: HashMap<Int, String>

class MovieViewHolder(var view: ItemMovieTvshowBinding, val context: Context) :
    RecyclerView.ViewHolder(view.root) {

}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val view = DataBindingUtil.inflate<ItemMovieTvshowBinding>(
        inflater,
        R.layout.item_movie_tvshow,
        parent,
        false
    )
    return MovieViewHolder(view, parent.context)
}

override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
    //...
}

override fun getItemCount(): Int {
    return movieList.size
}

}

CodePudding user response:

You can make a constructor in your adapter and pass the context by it. Or you can define a static contex in Application class and use it everywhere.

CodePudding user response:

In common case you shouldn't use context as a local variable.

You can access context inside onBindViewHolder, onCreateViewHolder, where you get views (binding).

But for your task you can add some variable like private var context: Context? = null or private var isGenreInitialized = false, then initialize genrePreferences for the first time when you get a view.

Don't use lateinit in almost all situations, it can lead to different bugs.

Or you can pass context via class constructor:

class MovieAdapter(private val context: Context, private val movieList: ArrayList<Movie>)
  • Related