Ronak Patel Ronak Patel - 3 months ago 21
Java Question

method call from adapter class to activity

Adapter:

check_list_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JPrequirements.prepareSelection(v, getAdapterPosition());
}
});


JPrequirements
is the activity. and
prepareSelection
is non-static method inside activity. I cannot access it from adapter.

ERROR:


non static method cannot be referenced from a static context


Which is right. that's why I tried with:

JPrequirements().prepareSelection(v, getAdapterPosition()); // Creating an instance...


But, the problem is I lost all activity component here. eg. layout components and other supporting variables. I don't want that. What is the best way to deal with this? How can I get updated value from adapter to activity? So, I can display it real-time.

Thanks.

Answer

You can achieve this via interface. Firstly, define an interface class as:

public interface ActivityAdapterInterface {
    public void prepareSelection(View v, int position);
}

Now, implement the interface in your Activity as:

public class JPrequirements extends AppCompatActivity implements ActivityAdapterInterface {
    ...
    public void prepareSelection(View v, int position) {
        // cool stuff here
    }
    ...
}

Make sure you pass this interface reference to your Adapter via its constructor. Then finally call it on click as:

check_list_item.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) {
        mActivityAdapterInterface.prepareSelection(v, getAdapterPosition());
    } 
}); 

[EDIT]

To provide the interface to your Adapter provide it the constructor.

public class YourAdapter ... {

    private ActivityAdapterInterface mActivityAdapterInterface;

    public YourAdapter(..., ActivityAdapterInterface activityAdapterInterface) {
        activityAdapterInterface = mActivityAdapterInterface;
    }

}
Comments