Search code examples
androidtoast

How I can have a custom Toast with a public static class


I created the following so as to control the several cases of toast messages

public class ExtraUtils {

public static Activity MyActivity;
public static LayoutInflater mInflater;

public static void MyToast(View view,int ToastCase) 
{
    Context context=MyActivity.getApplicationContext();
    mInflater = LayoutInflater.from(context);

    View customToastroot =mInflater.inflate(R.layout.custom_toast, null);
    Toast customtoast=new Toast(context);
    TextView text = (TextView) customToastroot.findViewById(R.id.txtToast);
    // Set the Text to show in TextView
    switch(ToastCase)
    {
        case 1:
            text.setText("You cannot Select this Again");
            break;
        case 2:
            text.setText("Oops Something went wrong");
            break;
    }
}
}

And I call it like ExtraUtils.MyToast(view,1) but I get a null exception at

Context context=MyActivity.getApplicationContext();

Solution

  • Change

    Context context = MyActivity.getApplicationContext();

    to

    Context context = MyActivity.this;

    Edit

    Sorry, I thought you are writing the code in the MyActivity itself. What you need to do is,

    public static void MyToast(View view,int ToastCase, Context context)
    

    and in MyActivity from where you are calling it do,

     ExtraUtils.MyToast(view, 1, MyActivity.this)