user7616014
user7616014

Reputation: 1

How can I use AlertDialog in an Adapter class?

I have send the Context to the Adapter

public ImageAdapter(Context context, List<Image> imagesList) {
        this.context = context;
        mImageList = imagesList;
    }

And I use AlertDialog this way:

AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AlertDialogCustom);

But I got error:

Unable to add window -- token null is not valid; is your activity running?

Upvotes: 0

Views: 889

Answers (3)

fan zhang
fan zhang

Reputation: 1

you should pass Activity instead of Context to the constructor of AlertDialog.Builder.and You have to make sure the activity is running when the dialog is running

Upvotes: 0

Mahmoud Ramadan
Mahmoud Ramadan

Reputation: 44

To do that you need to define call back.

  • define interface(callback with method )
  • implement this call back in activity that holds adapter
  • define object as parameter for your adapter like

    public ImageAdapter(Context context, List imagesList, Callback callback) { this.context = context; mImageList = imagesList; this.callback =callback; }

  • inside your adapter call method inside your call back as you want your activity will listen to this action and inside this method in your activity you can create your alert dialog

Upvotes: 0

AAA
AAA

Reputation: 505

send context as ActivityName.this/getActivity() from activity/fragment accordingly where you calling your adapter

Upvotes: 2

Related Questions