How to use Toast when I cant use "this" as context
Solution 1
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).
Solution 2
If you are in the inner Class then try this also
getApplicationContext()
Solution 3
You can use NameOfYourActivity.this
For example:
public class MyActivity extends Activity {
...
Toast.makeText(MyActivity.this, text, duration).show();
Solution 4
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.
Solution 5
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();
Related videos on Youtube
Comments
-
Seth Hikari over 3 years
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?-
Jim Blackler about 13 yearsCan you post the activity code and the error message? You should be able to get a valid context from within an Activity.
-
Seth Hikari about 13 years
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (mylocationlistener, String, int)
-
Seth Hikari about 13 yearsI have decided that I will make the locationlistener a sub class in the activity
-
-
Seth Hikari about 13 yearsthe activity is a
locationlistener
so it gives the error The methodmakeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (mylocationlistener, String, int)
-
MByD about 13 years@Seth - locationlistener is not an activity.
-
ccheneson about 13 yearsYou should paste your code to your OP , it will be easier for us to help you.
-
Rodrigo Recio about 5 yearsMakes 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();