maryam p maryam p - 3 months ago 8
Android Question

Cannot show a Toast in Android

I want show Toast when

toast()
is called, but it's not showing a Toast.

This is my code:

void callcalltoast() {
...
calltoast();
...
}
void calltoast() {
...
toast();
...
}
void toast() {
Log.i("LOG", "this is toast");
Toast.makeText(getBaseContext(),"this is toast",
Toast.LENGTH_SHORT).show();
}


I call toast in two other functions:

First call
callcalltoast()
then
calltoast()
then call
toast()


And this is log:

08-04 14:47:34.390: I/LOG(1796): this is toast
08-04 14:47:34.430: I/Choreographer(1796): Skipped 90 frames! The application may be doing too much work on its main thread.
08-04 14:47:34.451: W/InputMethodManagerService(285): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@41a1c750 attribute=null, token = android.os.BinderProxy@419ff990


I have tested using this:

void toast() {
Log.i("LOG", "this is toast");
Toast.makeText(getApplicationContext(),"this is toast",
Toast.LENGTH_SHORT).show();
}


this

void toast() {
Log.i("LOG", "this is toast");
Toast.makeText(this,"this is toast",
Toast.LENGTH_SHORT).show();
}


and

void toast() {
Log.i("LOG", "this is toast");
Toast.makeText(MainActivity.this,"this is toast",
Toast.LENGTH_SHORT).show();
}


But its not showing a Toast.

Answer

use this code

you can declare global variables Context context; and context=MainActivity.this; when Activity Create then when you call toast you can use context like toast(context);

public class MainActivity extends ActionBarActivity {

    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
        context=MainActivity.this;

        callcalltoast();
        ...
    }
    void callcalltoast() {
    ...
    calltoast();
    ...
    }
    void calltoast() {
        ...
        toast(context);
        ...
    }
    void toast(Context context) {
        Log.i("LOG", "this is toast");
        Toast.makeText(context,"this is toast",
                   Toast.LENGTH_SHORT).show();
    }
}
Comments