• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

How do I pass extra data from main activity to onBindViewHolder()?

RhinoCan

Well-Known Member
I've decided that when I present dates in my RecyclerView, I want the user to be able to see the dates in the format they want. Therefore, I have created a preference object for them that shows them several possibilities. All of the data for each item shown in the RecyclerView is coming from a MySQL database and the dates there are stored in YYYY-MM-DD format (e.g. 2018-08-01 for Aug 1, 2018). The Settings gives them the option of having the date in that format, 08/01/2018 or even as Wed Aug 1, 2018.

Since onBindViewHolder() needs to know the desired format of the date so that it can do the formatting, I either need to get that format in my main activity and pass it to onBindViewHolder() or pass it a reference to the SharedPreferences (it can't see them in the main activity from my Adapter). Unfortunately, I can't figure out how to do either.

I realize this is a generic technique, not something specific to Adapters but I've forgotten the technique and the vocabulary I need to search for it. Can anyone here remind me of the technique?

I had thought getting the preferred date format from the SharedPreferences in my main activity and then passing it to the Adapter might be easiest when I couldn't access the preferences directly (since I don't have a context) but even making the retrieved format public in the main activity doesn't make it visible in the Adapter.
 
Simply pass the SharedPreferences object into your Adapter class via its constructor. It's then accessible to all methods within that class.

Code:
MyAdapter adapter = new MyAdapter(SharedPreferences sharedPrefs);
 
Simply pass the SharedPreferences object into your Adapter class via its constructor. It's then accessible to all methods within that class.

Code:
MyAdapter adapter = new MyAdapter(SharedPreferences sharedPrefs);

Of course! For whatever reason, that just didn't occur to me. Thank you!
 
Back
Top Bottom