fweigl
fweigl

Reputation: 22018

Callback from (List)Adapter to Activity

I have an Actvivity with a ListView, I set an adapter

MyAdapter extends BaseAdapter

that adapter has a callback interface

OnPdfClickedListener callback; 

public interface OnPdfClickedListener {
    public void onPdfClicked();

}

and in the Activity

MyActvivity implements MyAdapter.OnPdfClickedListener

and

@Override
    public void onPdfClicked() {

    Log.d("TEST", "PDF CLICKED in ACTVIIVTY");

}

This is pretty much the same as described here, which works like charm for fragments. When trying the same from the adapter the callback object is null.

I also tried instantiating like

OnPdfClickedListener callback = new OnPdfClickedListener() {

    @Override
    public void onPdfClicked() {
        // TODO Auto-generated method stub

    }
};

I have no errors then but the respective method in the Activity is never called.

My question is 1. why isn't the callback object null when used in a fragment, it's never instantiated

and 2. how can I callback to an Activity from an adapter?

Upvotes: 0

Views: 7327

Answers (2)

DroidBender
DroidBender

Reputation: 7892

Try adding this:

In your Activity which implements the interface:

new MyAdapter(this,....);

In your Adapter:

MyAdapter(Context context, ...){
  callback = (OnPdfClickedListener)context;
}

Upvotes: 0

user
user

Reputation: 87064

  1. why isn't the callback object null when used in a fragment, it's never instantiated

Your Activity most likely isn't registered as a listener, with the callback variable you created(which has nothing to do with the Activity) an instance of OnPdfClickedListener and (probably) used that when the event happened.

how can I callback to an Activity from an adapter?

Pass a reference to the Activity to your MyAdapter class, cast it to OnPdfClickedListener and use that to call onPdfClicked instead of the current callback variable.

Upvotes: 3

Related Questions