I have a location listener activity and I want to make toast notifications. But it will not let me pass this
as the context. How should I make toast work?

- 2,711
- 6
- 27
- 32
-
1Can you post the activity code and the error message? You should be able to get a valid context from within an Activity. – Jim Blackler Apr 12 '11 at 20:19
-
`The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (mylocationlistener, String, int)` – Seth Hikari Apr 12 '11 at 20:26
-
I have decided that I will make the locationlistener a sub class in the activity – Seth Hikari Apr 12 '11 at 20:34
7 Answers
If the toast is located inside your activity class, you could use YourActiviy.this
where YourActivity
is the class name. If it's outside your class, you'll need to get your activity context (pass it in the constructor etc).

- 59
- 8

- 135,866
- 28
- 264
- 277
-
1Makes sense. For example, in my situation, the solution below is similar to what he described above: `Toast.makeText(getActivity().getApplicationContext(), "Pressed.", Toast.LENGTH_SHORT).show();` – Rodrigo Recio Apr 09 '19 at 22:14
You can use NameOfYourActivity.this
For example:
public class MyActivity extends Activity {
...
Toast.makeText(MyActivity.this, text, duration).show();

- 49,072
- 8
- 63
- 68
-
the activity is a `locationlistener` so it gives the error The method `makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (mylocationlistener, String, int)` – Seth Hikari Apr 12 '11 at 20:28
-
-
You should paste your code to your OP , it will be easier for us to help you. – ccheneson Apr 12 '11 at 21:02
instead try getApplicationContext()
Toast tea = Toast.makeText(getApplicationContext(), "Send", Toast.LENGTH_LONG);
tea.show();

- 1,265
- 14
- 18
Field variable: Context context;
inside OnCreate: context = this;
Xamarin / C# Syntax:
Toast.MakeText(context, "your message", ToastLength.Long).Show();
Android / Java syntax:
Toast.makeText(context, "your message", Toast.LENGTH_LONG).show();

- 3,444
- 5
- 37
- 53

- 21
- 1
For example, if you have a listener with a method called "onComplete" inside it, this code should work.
public void onComplete(String response, Object state) {
final String response_complete = response;
MyActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MyActivity.this, text, duration).show();
}
});
}
That should do it.

- 356
- 1
- 6
It sounds like you are in an inner class in the Activity. If thats the case, try ActivityName.this.

- 4,648
- 2
- 27
- 26