Call Activity method from adapter

call fragment method from adapter
call activity method from recyclerview adapter kotlin
how to call activity from recyclerview adapter in android
how to create interface between activity and adapter in android
how to start activity in adapter class
adapter to activity intent in android
kotlin start activity from adapter
start activity from adapter class android

Is it possible to call method that is defined in Activity from ListAdapter?

(I want to make a Button in list's row and when this button is clicked, it should perform the method, that is defined in corresponding Activity. I tried to set onClickListener in my ListAdapter but I don't know how to call this method, what's its path...)

when I used Activity.this.method() I get the following error:

No enclosing instance of the type Activity is accessible in scope

Any Idea ?

Yes you can.

In the adapter Add a new Field :

private Context mContext;

In the adapter Constructor add the following code :

public AdapterName(......, Context context) {
  //your code.
  this.mContext = context;
}

In the getView(...) of Adapter:

Button btn = (Button) convertView.findViewById(yourButtonId);
btn.setOnClickListener(new Button.OnClickListener() {
  @Override
  public void onClick(View v) {
    if (mContext instanceof YourActivityName) {
      ((YourActivityName)mContext).yourDesiredMethod();
    }
  }
});

replace with your own class names where you see your code, your activity etc.

If you need to use this same adapter for more than one activity then :

Create an Interface

public interface IMethodCaller {
    void yourDesiredMethod();
}

Implement this interface in activities you require to have this method calling functionality.

Then in Adapter getView(), call like:

Button btn = (Button) convertView.findViewById(yourButtonId);
btn.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (mContext instanceof IMethodCaller) {
            ((IMethodCaller) mContext).yourDesiredMethod();
        }
    }
});

You are done. If you need to use this adapter for activities which does not require this calling mechanism, the code will not execute (If check fails).

Call an Activity method from inside adapter?, I Recommending on using interface as listener. For example: 1, create your interface: public interface MyListener { void folderClicked(); }. You need to be sure that activity is created. to call that function from Adapter just simply do : YourActivity.moveDownFolder()

You can do it this way:

Declare interface:

public interface MyInterface{
    public void foo();
}

Let your Activity imlement it:

public class MyActivity extends Activity implements MyInterface{
    public void foo(){
        //do stuff
    }
}

Then pass your activity to ListAdater:

public MyAdapter extends BaseAdater{
    private MyInterface listener;

    public MyAdapter(MyInterface listener){
        this.listener = listener;
    }
}

And somewhere in adapter, when you need to call that Activity method:

listener.foo();

Call Activity method inside adapter, This is simple and most common tip for every one because most of time we need to call a activity method inside adapter to pass data etc… If you need to use this same adapter for more than one activity then : Create an Interface. public interface IMethodCaller{ void yourDesiredMethod(); } Implement this interface in activities you require to have this method calling functionality. Then in Adapter getView() , call like :

Original:

I understand the current answer but needed a more clear example. Here is an example of what I used with an Adapter(RecyclerView.Adapter) and an Activity.

In your Activity:

This will implement the interface that we have in our Adapter. In this example, it will be called when the user clicks on an item in the RecyclerView.

public class MyActivity extends Activity implements AdapterCallback {

    private MyAdapter myAdapter;

    @Override
    public void onMethodCallback() {
       // do something
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myAdapter = new MyAdapter(this);
    }
}
In your Adapter:

In the Activity, we initiated our Adapter and passed this as an argument to the constructer. This will initiate our interface for our callback method. You can see that we use our callback method for user clicks.

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private AdapterCallback adapterCallback;

    public MyAdapter(Context context) {
        try {
            adapterCallback = ((AdapterCallback) context);
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement AdapterCallback.", e);
        }
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
        // simple example, call interface here
        // not complete
        viewHolder.itemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    adapterCallback.onMethodCallback();
                } catch (ClassCastException e) {
                   // do something
                }
            }
        });
    }

    public static interface AdapterCallback {
        void onMethodCallback();
    }
}

[SOLVED] Call Activity method from adapter, Yes you can. In the adapter Add a new Field : private Context mContext;. In the adapter Constructor add the following code : If you need to use this same adapter for more than one activity then : Create an Interface. public interface IMethodCaller { void yourDesiredMethod(); } Implement this interface in activities you require to have this method calling functionality. Then in Adapter getView (), call like: Button btn = (Button) convertView.findViewById(yourButtonId); btn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { if (mContext instanceof IMethodCaller

Basic and simple.

In your adapter simply use this.

((YourParentClass) context).functionToRun();

How to finish an activity from an Adapter..?, how to call activity from adapter class in android finish activity from fragment finish activity from context call activity method from adapter how to finish previous � You can call Activity method by using instance of Activity like this, inside MainActivity write below code . mDeviceListAdapter = new DeviceListAdapter(MainActivity.this); Inside Adapter. private MainActivity _mainActivity; public DeviceListAdapter(MainActivity activity){ this._mainActivity=activity; } Inside your onClick method

One more way is::

Write a method in your adapter lets say public void callBack(){}.

Now while creating an object for adapter in activity override this method. Override method will be called when you call the method in adapter.

Myadapter adapter = new Myadapter() {
  @Override
  public void callBack() {
    // dosomething
  }
};

android - Call Activity method from adapter, Is it possible to call method that is defined in Activity from ListAdapter ? (I want to make a Button in list's row and when this button is clicked, it should perform the� Solution 1 : Make the adapter an inner class of your fragment, so that you can call the method directly. Solution 2 : Update your adapter constructor to accept the Fragment as a parameter. Something like : customAdapter = new CustomAdapter(myContext, android.R.layout.simple_list_item_1, getList, HomeFragment.this);

How to call Main Activity method in another class in Android, It could be that the answer involves passing a reference to your Activity to another class, or using an interface , or using an EventBus like LocalBroadcastManager , � If you are referring to something like: [code ]new MainActivity().doMyMethod();[/code] then this isn’t possible. The actual answer depends entirely on what you are trying to achieve.

Passing Lambda Function for Adapter Callback in Kotlin, Of course you created this pesky interface! with ONE method inside it it inside your Activity, while passing it into your adapter via constructor. If a menu appears, select Import class. Return to the activity_main.xml file to call the method from the button: Select the button in the Layout Editor. In the Attributes window, locate the onClick property and select sendMessage [MainActivity] from its drop-down list.

How to pass Activity object into onBindViewHolder method for using , method call from adapter class to activity, You can achieve this via interface . Firstly, define an interface class as: public interface ActivityAdapterInterface { public�

Comments
  • you cannot call activity.this in some other class unless it is a inner class to that activity. follow @Eldhose M Babu solution for your case
  • As this is a popular question, I would strongly suggest NOT TO USE this solution. You should avoid class casting here, because this might lead to runtime exceptions.
  • Eldhose bro, I have nothing against you but answer below is best practice. You can even read in comments. You should not cast mContext to your Activity as you are avoiding reuse of code. Now this adapter can only be used inside the Activity which you have casted your mContext variable to, where if you have a listener defined then you can reuse the same Adapter in another Activity. Trust me i have spent enough time in industry and I am just trying to help you here, please don't take it personally.
  • This solution is one of the best I've ever found on SO. So thanks a lot Mr. Babu. Calling the Activity's methods by this, gives the whole app a 500% kicking performance boost -> I don't need to reload the database in the adapter, which I need to access. I don't care about "years in industry", I'm looking for stable and working solutions and I'm quite sure, I will not find a better way to get access. Maybe I could set up the DB as a singleton, but this is not the way I want to "un-structure" my project.
  • @RAM if you need to call the same method in more than one activity, you need to create an interface with that method name. Then implement that interface in what all activities you need the method call to be availed. Then in the click listener, check instance of your interface rather than using activity name.
  • Superb answer. Thumbs up
  • I first thought of the method above as you would with fragments but this is the best solution!
  • wich is my InterfaceListener? how can initialize it ? public MyAdapter(MyInterface listener){ this.listener = listener; }
  • How do you pass the interface to the adapter though (from the Activity)
  • @Brandon you can pass it is constructor parameter in adapter.