Get an Activity in a Adapter – Android studio in Java

I’m a newbie developer, I’m trying to use Heyzap / Fyber Ads mediation, and I need some help with this:

I have an Adapter class (that isn’t an Activity) used for a RecyclerView.

I’ve been using view.getContext() on many places for the context, but now it asks for “Activity”

This Adapter class contains two OnClickListeners where i need to insert this:

InterstitialAd.display(// I need to insert "Activity" here);

I’ve been tried with:

this
Activity.this (constructor & adapter)
Activity.class (constructor & adapter)
view.getActivity()


///And 999x other combinations.

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

I would suggest to have an interface for communication with the activity. This way you can shift all the code concerning the view “onClick” to the activity/fragment layer itself where they should be IMO.

Here is a tutorial around the same https://android.jlelse.eu/click-listener-for-recyclerview-adapter-2d17a6f6f6c9

Jason
Guest

A context can be an activity, so you could cast it. Even better, test it first to make sure it’s an activity and then cast it. You could create a helper method to do the work for you:

private static Activity getActivity(View view) {
    if (view.getContext() instanceof Activity) {
        return (Activity)view.getContext();
    }
    return null;
}