How to use Toast when I cant use "this" as context

43,111

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

Share:
43,111

Related videos on Youtube

Seth Hikari
Author by

Seth Hikari

Learning to be an engineer.

Updated on November 11, 2020

Comments

  • Seth Hikari
    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
      Jim Blackler about 13 years
      Can you post the activity code and the error message? You should be able to get a valid context from within an Activity.
    • Seth Hikari
      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
      Seth Hikari about 13 years
      I have decided that I will make the locationlistener a sub class in the activity
  • Seth Hikari
    Seth Hikari about 13 years
    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)
  • MByD
    MByD about 13 years
    @Seth - locationlistener is not an activity.
  • ccheneson
    ccheneson about 13 years
    You should paste your code to your OP , it will be easier for us to help you.
  • Rodrigo Recio
    Rodrigo Recio about 5 years
    Makes 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();