Reputation: 533
I want to display a toast message in a static class but the is an issue of Toast message parameter passing context of application. Pleas help me, how to display the toast message in static class. Please recommend me the change that I have need to do, I will be very thankful to you. Here is a portion of my code.
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_four_position);
mEndlessRunnable = (Runnable) new UpdateRunnable();
mEndlessRunnable.run();
}
private static class UpdateRunnable implements Runnable {
private int mState;
public UpdateRunnable(Handler handler, Button[] buttons) {
mHandler = handler;
mButtons = buttons;
}
public void run() {
switch (mState) {
case 0:
mState = 1;
break;
case 1:
mState = 0;
// Here is the issue in my toast message
Toast.makeText(CONTEXT, "Toast message.",Toast.LENGTH_LONG).show();
break;
}
mHandler.postDelayed(this,1000));
}// End of run()
}//End of class UpdateRunnable
} //End of MainActivity
Upvotes: 0
Views: 350
Reputation: 877
I guess getParent() or getApplicationContext() should do the work pass the parameter to the class and have a local context object .Let me know if it fails
Upvotes: 0
Reputation: 13390
Well, one of the way is to use a static variable in your activity.
public static Context myContext;
then update it in onCreate..
onCreate()
{
myContext = getApplicationContext();
}
Other way is to pass the context in the constructor of your class...
Upvotes: 0
Reputation: 761
you can try to make a separate method for your toast
public void showToast(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}//end showToast
and then call that in your inner class.
Upvotes: 1
Reputation: 48272
You can pass your Activity's Context to your UpdateRunnable class in constructor and use it then in your run() function.
However if you are showing Toast from an inner class then that inner class, probably, shouldn't be a static class at all. You can remove static keyword and use your Activity's getContext() in run() then.
Why do you want your inner class static?
Upvotes: 1