'How to display Toast in Android?

I have a slider that can be pulled up and then it shows a map. I can move the slider up and down to hide or show the map. When the map is on front, I can handle touch events on that map. Everytime I touch, a AsyncTask is fired up, it downloads some data and makes a Toast that displays the data. Although I start the task on touch event no toast is displayed, not till I close the slider. When the slider is closed and the map is not displayed anymore the Toast appears.

Any ideas?

Well start the task

EDIT:

public boolean onTouchEvent(MotionEvent event, MapView mapView){ 
    if (event.getAction() == 1) {
        new TestTask(this).execute();
        return true;            
    }else{
        return false;
    }
 }

and in onPostExecute make a toast

Toast.makeText(app.getBaseContext(),(String)data.result, 
                Toast.LENGTH_SHORT).show();

In new TestTask(this), this is a reference to MapOverlay and not to MapActivity, so this was the problem.



Solution 1:[1]

In order to display Toast in your application, try this:

Toast.makeText(getActivity(), (String)data.result, 
   Toast.LENGTH_LONG).show();

Another example:

Toast.makeText(getActivity(), "This is my Toast message!",
   Toast.LENGTH_LONG).show();

We can define two constants for duration:

int LENGTH_LONG Show the view or text notification for a long period of time.

int LENGTH_SHORT Show the view or text notification for a short period of time.

Customizing your toast

LayoutInflater myInflater = LayoutInflater.from(this);
View view = myInflater.inflate(R.layout.your_custom_layout, null);
Toast mytoast = new Toast(this);
mytoast.setView(view);
mytoast.setDuration(Toast.LENGTH_LONG);
mytoast.show();

Solution 2:[2]

Extending activity using baseadapter used this

Toast.makeText(getActivity(), 
    "Your Message", Toast.LENGTH_LONG).show();

or if you are using activity or mainactivity

Toast.makeText(MainActivity.this, 
    "Your Message", Toast.LENGTH_LONG).show();

Solution 3:[3]

Syntax

Toast.makeText(context, text, duration);

Parameter Value

context

getApplicationContext() - Returns the context for all activities running in application.

getBaseContext() - If you want to access Context from another context within application you can access.

getContext() - Returns the context view only current running activity.

text

text - Return "STRING" , If not string you can use type cast.

 (string)num   // type caste

duration

Toast.LENGTH_SHORT - Toast delay 2000 ms predefined

Toast.LENGTH_LONG - Toast delay 3500 ms predefined

milisecond - Toast delay user defined miliseconds (eg. 4000)


Example.1

Toast.makeText(getApplicationContext(), "STRING MESSAGE", Toast.LENGTH_LONG).show();

Example.2

Toast.makeText(getApplicationContext(), "STRING MESSAGE", 5000).show();

Solution 4:[4]

To toast in Android

Toast.makeText(MainActivity.this, "YOUR MESSAGE", LENGTH_SHORT).show();

or

Toast.makeText(MainActivity.this, "YOUR MESSAGE", LENGTH_LONG).show();

( LENGTH_SHORT and LENGTH_LONG are acting as boolean flags - which means you cant sent toast timer to miliseconds, but you need to use either of those 2 options )

Solution 5:[5]

You can customize your tost:

LayoutInflater mInflater=LayoutInflater.from(this);

View view=mInflater.inflate(R.layout.your_layout_file,null);
Toast toast=new Toast(this);
toast.setView(view);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();

Or General way:

Toast.makeText(context,"Your message.", Toast.LENGTH_LONG).show();

Solution 6:[6]

I have tried several toast and for those whom their toast is giving them error try

Toast.makeText(getApplicationContext(), "google", Toast.LENGTH_LONG).show();

Solution 7:[7]

There are two ways to do it.

Either use the inbuilt Toast message

//Toast shown for  short period of time 
Toast.makeText(getApplicationContext(), "Toast Message", Toast.LENGTH_SHORT).show();

//Toast shown for long period of time
Toast.makeText(getApplicationContext(), "Toast Message", Toast.LENGTH_LONG).show();

or make a custom one by providing custom layout file

Toast myToast = new Toast(getApplicationContext());
myToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
myToast.setDuration(Toast.LENGTH_LONG);
myToast.setView(myLayout);
myToast.show();

Solution 8:[8]

I ran across the answers here, and was attracted by the fact that there seems to be someone poking around, believing that an Activity context is required. This is not the case. However, it is a requirement that a Toast is posted from the main event or UI Thread. So, getting this to work outside of an activity context is a little bit tricky. Here is an example that would work inside of a system service, or any potential class that ultimately inherits from Context.

public class MyService extends AccessibilityService {

    public void postToastMessage(final String message) {
        Handler handler = new Handler(Looper.getMainLooper());

        handler.post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }
}

Note that we do not need access to an instance of Activity for this to work. Please stop suggesting this is the case! If Activity were required, the method signature wouldn't call for a Context.

Solution 9:[9]

Toast.makeText(app.getBaseContext(),"your string",Toast.LENGTH_SHORT).show();

instead of using "app.getBaseContext()".

You can try using "getApplicationContext()" or "getContext()".

If your code is in activity then you should use "this" of "Activty.this".
If your code is in fragment then you should go for "getActivity()"

Solution 10:[10]

If it's fragment,

Toast.makeText(getActivity(), "this is my Toast message!!! =)",
                   Toast.LENGTH_LONG).show();

Solution 11:[11]

For displaying Toast use the following code:

Toast toast = new Toast(getApplicationContext());

toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

toast.setDuration(Toast.LENGTH_LONG);

toast.show();

Solution 12:[12]

 Toast toast=Toast.makeText(getApplicationContext(),"Hello", Toast.LENGTH_SHORT);
 toast.setGravity(Gravity.CENTER, 0, 0); // last two args are X and Y are used for setting position
 toast.setDuration(10000);//you can even use milliseconds to display toast
 toast.show();**//showing the toast is important**

Solution 13:[13]

Simple Way

toast("Your Message")

OR

toast(R.string.some_message)

Just add two methods in your BaseActivity. Or create new BaseActivity if you are not already using.

public class BaseActivity extends AppCompatActivity {
    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void toast(@StringRes int msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}

and extend all your activities by BaseActivity.

public class MainActivity extends BaseActivity

Solution 14:[14]

enter image description here

Must read: Android Toast Example

Syntax

Toast.makeText(context, text, duration);

You can use getApplicationContext() or getActivity() or MainActivity.this(if Activity Name is MainActivity)

Toast.makeText(getApplicationContext(),"Hi I am toast",Toast.LENGTH_LONG).show();

or

Toast.makeText(MainActivity.this,"Hi I am Toast", Toast.LENGTH_LONG).show();

Solution 15:[15]

Inside Fragments (onCreateView)

Toast.makeText(getActivity(), "your message" , Toast.LENGTH_LONG).show();

Inside Classes (onCreate)

Toast.makeText(myClassName.this, "your message" , Toast.LENGTH_LONG).show();

Solution 16:[16]

Simplest way! (To Display In Your Main Activity, replace First Argument for other activity)

Button.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v){
        Toast.makeText(MainActivity.this,"Toast Message",Toast.LENGTH_SHORT).show();
    }
}

Solution 17:[17]

The Getting Started Way

Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT).show();

Solution 18:[18]

This worked for me:

Toast.makeText(getBaseContext(), "your text here" , Toast.LENGTH_SHORT ).show();

Solution 19:[19]

Here's another one:

refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getBaseContext(),getText(R.string.refresh_btn_pushed),Toast.LENGTH_LONG).show();
            }
        });

Where Toast is:

Toast.makeText(getBaseContext(),getText(R.string.refresh_btn_pushed),Toast.LENGTH_LONG).show();

& strings.xml:

<string name="refresh_btn_pushed">"Refresh was Clicked..."</string>

Solution 20:[20]

Show Toast from Service

public class ServiceA extends Service {
    //....
    public void showToast(final String message) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }
    //....
}

You can also put showToast method in your Application class, and show toast from anywhere.

Solution 21:[21]

If you want to write a simple toast in your activity: Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();

1.Showing TextView in Toast:---

TextView tv = new TextView(this); tv.setText("Hello!"); tv.setTextSize(30); tv.setTextColor(Color.RED); tv.setBackgroundColor(Color.YELLOW);

2.Showing Image as Toast:--

ImageView iv = new ImageView(this); iv.setImageResource(R.drawable.blonde); Toast t = new Toast(this); t.setView(iv); t.setDuration(Toast.LENGTH_LONG); t.show();

3.showing Layout as Toast:--

LayoutInflater li = getLayoutInflater(); View view = li.inflate(R.layout.my_toast_layout,null,false); Toast t = new Toast(this); t.setView(view); t.setDuration(Toast.LENGTH_LONG); t.show();

** If you want to write the toast in your Async then: private Activity activity; private android.content.Context context; this.activity = activity; this.context = context; Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();

Solution 22:[22]

Extension function with some kotlin sugar

fun Context.showToast(string: String){
    Toast.makeText(
        this, string,
        Toast.LENGTH_SHORT
    ).show()
}

Usage:

From Activity: showToast("toast)

From Fragment: requiredContext().showToast("toast)