SendBroadcast issue inside onCLickllistener

6.3k views Asked by At
btn2=(Button) rowView.findViewById(R.id.button1);
    btn2.setText("Find");

      btn2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
                    Intent Message1=new Intent();
                Message1.setAction("map");
                sendBroadcast(Message1);}

The error says the method of broadcast is undefined inside the oclicklistener. why is that?

4

There are 4 answers

0
Maxim On

Should be context.sendBroadcast(Intent). You can do CurrentActivity.this.sendBroadcast(Intent) Inside of OnClickListener there is no context instance that's why it cannot execute method of Context

0
Reed On

sendBroadcast can only be done under an Activity, BroadcastReceiver, or Service context, but you are trying to sendBroadcast in the onClick, which is not any of the previously mentioned contexts.

The easiest thing to do is:

CurrentActivity.this.sendBroadcast(Message1);

Another option is to create a class variable Context context and then in the onCreate (if it's an activity or service), put context = this, and then do context.sendBroadcast(Message1);. Or, if it's in a BroadcastReceiver, just do context.sendBroadcast(Message);

0
LuxuryMode On

You've created an OnClickListener as an anonymous class. Inside of this anonymous instance, you're trying to call sendBroadcast() and the compiler is trying to find such a method in OnClickListener, but there is no such method. What you need is to reference the enclosing class, namely the Activity by doing ThisActivity.this.sendBroadcast(intent), where ThisActivity is the actual name of your Activity.

1
Bilal Ahmad On

In Fragments

Intent signalIntent = new Intent("updateBTN");
signalIntent.putExtra("key", "value");
getActivity().sendBroadcast(signalIntent);