SendBroadcast issue inside onCLickllistener - android

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?

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

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.

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);

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

Related

why am i getting error when trying to open new activity in android studio

I'm getting this error when I write the intent inside the onCreate method.
But when I write the intent inside an outer method and call it, it works.
Button click listener is an interface and you implemented it here as an anonymous class, so inside of that class this refers to that anonymous class, not your activity class, but Intent constructor needs activity class implementation, therefore as #ADITYA RANADE answered you need to change it to MainActivity.this.
However if you replace anonymous class with lambda you can avoid this:
Button button = new Button(context);
button.setOnClickListener(v -> {
Intent intent = new Intent(this, MainActivity.class);
});
Change it to MainActivity.this inside the intent
Well that is because of the place or more precisely "context" (not the androidish Context) of where you are calling it.
When you call it from the anonymously created inner class which implements the listener for a view click, so in this case the this represents something else - anonymous class.
But on the other side when you make the method e.g. openScheduleActivity() inside the activity itself, the this keyword represents the activity itself and in fact represents the androidish Context or in this particular case even the activity. So you can either stay with case that you have already had there and slightly edit it, or you can use lambda expression, or you can use the method inside the activity itself as you have already discovered.
edited case:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, schedule.class);
startActivity(intent);
}
});
lambda expression:
button.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, schedule.class);
startActivity(intent);
});

How to get activity instance from startActivity() or precisely how to call a method in an activity that we create?

Im trying to figure a way how to call an activity that an adapter has started. Is there a way to get the instance of the activity from startactivity and make a method call into the activity ?
I'ved got an adapter that has a list
public class LanguageDownloadRVAdapter extends RecyclerView.Adapter<LanguageDownloadRVAdapter.DownloadViewHolder>{
And in this adapter, it starts a particular activity called MainActivity
context.startActivity(new Intent(context, MainActivity.class));
((Activity)context).finish();
Here is the MainActivity that it starts
public class MainActivity extends AppCompatActivity implements IabBroadcastListener{
How can I make a call from the adapter to a method in the MainActivity. (im just trying to perform inapp purchase which is implemented in the MainActivity). so how can i do something like this.
mainactivity.perform_inapp_purchase();
Try to use EventBus for passing data between activity and list adapter. You can do it in the same way for passing data between activity and fragment.
This work the same way as storing data in global variable (in a fancier way)
In the adapter:
Add a new Field private Context mContext;
In the adapter Constructor add one more parameter as below, and assign it into class level variable:
public LanguageDownloadRVAdapter(......,Context context){
//your code.
this.mContext=context;
}
In the Adapter where you want to call Activity's perform_inapp_purchase() method:
if(mContext instanceof MainActivity){
((MainActivity) mContext).perform_inapp_purchase();
}
More Generalized Approach:
If you need to use this same adapter for more than one activity then :
Create an Interface
public interface InAppPerchaceInterface{
void perform_inapp_purchase();
}
Implement this interface in activities
Then in Adapter, call like below:
if(mContext instanceof InAppPerchaceInterface){
((InAppPerchaceInterface) mContext).perform_inapp_purchase();
}
You can store the instance in the application class, but you should be careful about the memory leaks.
In the onCreate of your activity
protected void onCreate(Bundle savedInstanceState)
{
// get the instance using this and store it in the application class or in the place that you want to call from it
}
From where will you call your method?
I didn't understand the situation.

Error in calling StartService while in setOnClickListener onCreate

I have an activity which calls a service through
startService(new android.content.Intent(this,NeglectedService.class);
I am trying to add a ToggleButton, that while isChecked(True) the service will run, and vice versa.
toggleService = (ToggleButton)findViewById(R.id.btnStopStartService);
toggleService.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(toggleService.isChecked())
{
// Start the service
showToast("true");
startService(new Intent(this,NeglectedService.class));
}
else
{
// Pause/Stop the service
showToast("false");
}
}
});
But calling this way returns an error, I don't know how to tackle
The constructor Intent(new View.OnClickListener(){}, Class<NeglectedService>) is undefined
If I remove the new Intent(this, NeglectedService.class) than the error dissappears, but the service is not called (ofc, the activity doesn't know who to call)
So, my question:
- How can I monitor and start/stop a service from my activity?
Question: How can I control a service state from the activity that created it?
I have a togglebutton.onclicklistener. I want that when the toggle is ON, the service will run, and stop wehn toggled to off.
I will use sharedpreferences to store the service state, but I get an error when calling startService(new android.content.Intent(this,NeglectedService.class); from the if(toggleService.isChecked())
The constructor that you are trying to use takes a Context as its first argument, but this isn't an instance of Context, it's the anonymous on-click listener that you are declaring. To pass the outer instance you need to qualify it:
startService(new Intent(MyActivity.this, NeglectedService.class));
where MyActivity is the name of your activity class.
Your problem is the scope of this in your Intent instantiation. Where you are calling it,this refers to an instance of View.OnClickListener, but it needs to be an instance of android.content.Context.
I do not know the name if your Activity which contains the code snippet that you have included, but if is named MyActivityClassthen you need to replace thiswith MyActivityClass.this.

Starting an Android Activity from an Listener defined in an external class file

I have an Activity MyActivity with a Button MyButton.
I want to attach a MySpecialOnClickListener to MyButton.
I write MySpecialOnClickListener in an external class file.
public class MySpecialOnClickListener extends ButtonHandler implements OnClickListener {
public OnClickListenerWithSpeech (Context context)
{ super.context = context; }
#Override
public void onClick(View view) { handleClick(view); }
}
and ButtonHandler looks like this
public abstract class ButtonHandler {
protected Context context;
protected void handleClick (View view){
if (view.getid()==R.id.button_B) {
context.startActivity (new Intent(context, ActivityC.class));
}
}
}
I basically want to store all logic for Buttons in the ButtonHandler.
SO...as I said, I have the MySpecialOnClickListener defined in an external class file.
When I click MyButton I get the following fatal error.
Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
So I can't start an activity normally from within a non-Activity. Fair enough.
However, if I change MySpecialOnClickListener to be an inner class in 'MyActivity' it works fine. Remember 'ButtonHandler' is still an external class file. So it (where ActivityC is ultimately started from) doesn't change.
My question (finally) is: can someone explain the logic of why one is allowed and the other isn't. I presume its a scoping thing or something but I'm a bit confused. It seems the code to start the process of starting an activity has to literally be inside another Activity.
EDIT - PROBLEM SOLVED
See below. The location of the class is irrelevant. I just didn't pass in the context properly.
because the ButtonHandler 'context' field isn´t associated with any activity context. So, when you attach the MySpecialOnClickListener instance to a button you create it passing the context parametener, isn´t???
something like this:
MySpecialOnClickListener listener = new MySpecialOnClickListener(MyActivity.this);
aButton.setOnClickListener( listener );
in this way you´re constructing the Button with the correct context...
It's likely that you are not passing the Activity context to MySpecialOnClickListener. Could you show me the difference in the way you invoke the inner-class approach?
Apologies to those of you who tried to answer. It was my fault (and I didn't include the following info initially for people)
When I was passing in the context to the 'MySpecialOnClickListener' I would do:
view.setOnClickListener(new MySpecialOnClickListener(getApplicationContext()));
when I should have done:
view.setOnClickListener(new MySpecialOnClickListener(this));
So getApplicationContext() doesn't seem to get the "correct" context for the app.
Which leads me to my next question as to what getApplicationContext() actually returns :)

Calling an activity from a custom dialog

I guess this is just a simple question (I’m such a noob…)
I have this custom dialog box that has 3 buttons in it.
Now I want to call an activity from one of the buttons so
I tried this:
public class picturedialog extends Dialog implements OnClickListener {
Button Camera;
public picturedialog (Context context){
super (context);
setContentView(R.layout.picturedialog);
Camera = (Button) this.findViewById(R.id.pdButton1);
Camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
dismiss();
Intent myIntent = new Intent(view.getContext(), CameraActivity.class);
startActivity(myIntent);
}
});
...
}
Then the red squiggly line appears on startActivity(myIntent).
Upon hovering on it, eclipse tells me this: “The method startActivity(Intent) is undefined for the type new View.OnClickListener(){}”
Ehhh? Please orient me on how to do this properly.
Any help would be appreciated.
Suppose the name of your Activity is A, then you just do:
A.this.startActivity(myIntent);
The problem arises because "this" inside your inner class refers to the object of that inner class, when what you want is the object of the enclosing Activity. A.this will refer to that.
If you aren't enclosing this class in an Activity, then try calling the startActivity from method using the context that you passed into the method, e.g. context.startActivty(myIntent).
The startActivity method belongs to the Context class.
I am sure you are overcomplicating with subclassing from Dialog. Try to follow to the dialog tutorial - https://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog
Note that dialogs are created on the fly (in Activity.onCreateDialog()) without the need to have your own custom dialog classes. Since you set a listener being inside of the wrapping activity (if you follow the tutorial), then you are able to call startActivity(myIntent), because all the fields/methods of a wrapping class instance are available for an instance of an inner class.

Categories

Resources