how to show toast message in not extend activity class

后端 未结 3 1708
小蘑菇
小蘑菇 2021-01-19 08:01

hi this is my helper class where i check internal connection and xml paersing and use this class to another activity the problem is when server connected is working fine b

相关标签:
3条回答
  • 2021-01-19 08:37

    Create myToast method in your application class, Like

    public void myToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    

    and add the following code to your class,

    private MyApplication application;
    public AgAppHelperMethods(Context context) {
      application = (MyApplication)context.getApplication();
    }
    

    Finally, call myToast method, where you want, like

    applicaion.myToast("msg you want to show");
    

    Note: replace MyApplication with your application class

    I have not tested, but this may work for u.

    0 讨论(0)
  • 2021-01-19 08:52

    You need to target your applicationContext in the toast,i can't see you doing that anywhere? And you have outcommented the first line of your toast message?

    Edit: Also really really bad codestyle to catch exception e. You should try to narrow down which kind of exception it is that you want to catch.

    0 讨论(0)
  • 2021-01-19 09:00

    Create a global variable like:

    Context mContext;
    

    Then add a constructor to your class, in which you accept a Context parameter and assign it to mContext like:

    public AgAppHelperMethods(Context context) {
          mContext = context;
    }
    

    Create an object in your Activity like:

    AgAppHelperMethods helper = new AgAppHelperMethods(getBaseContext());
    

    Finally, to show your Toast use:

     Toast.makeText(mContext, "error  server not responding " + e.getMessage(), Toast.LENGTH_LONG).show();
    
    0 讨论(0)
提交回复
热议问题