[android] 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.

This question is related to android android-mapview android-asynctask toast

The answer is


 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**

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.


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

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

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 )


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

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


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

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

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

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.


The Getting Started Way

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

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

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

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>


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


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


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

This worked for me:

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

If it's fragment,

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

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

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-mapview

How to add google-play-services.jar project dependency so my project will run and present map This app won't run unless you update Google Play Services (via Bazaar) Where is the Keytool application? How to display Toast in Android? How to draw a path on a map using kml file? Drawing a line/path on Google Maps

Examples related to android-asynctask

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference Android check null or empty string in Android java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState Android basics: running code in the UI thread How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? Android. Fragment getActivity() sometimes returns null android asynctask sending callbacks to ui AsyncTask Android example Return a value from AsyncTask in Android

Examples related to toast

How to create Toast in Flutter? java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(); Custom toast on Android: a simple example Use Toast inside Fragment Call to getLayoutInflater() in places not in activity How to display Toast in Android? How to change position of Toast in Android?