how to call non static method from static method i

2019-05-12 05:22发布

I am facing a big problem in calling non static method from static method.

This is my code

Class SMS
{
    public static void First_function()
    {
        SMS sms = new SMS();
        sms.Second_function();
    }

    public void Second_function()
    {
        Toast.makeText(getApplicationContext(),"Hello",1).show(); // This i anable to display and cause crash
        CallingCustomBaseAdapters();    //this was the adapter class and i anable to call this also
    }

I am able to call Second_function but unable to get Toast and CallCustomBaseAdapter() method, crash occurs.

What should I do to fix that issue ?

2条回答
smile是对你的礼貌
2楼-- · 2019-05-12 05:28
  public static void First_function(Context context)
  {
    SMS sms = new SMS();
    sms.Second_function(context);
  }

  public void Second_function(Context context)
  {
    Toast.makeText(context,"Hello",1).show(); // This i anable to display and cause crash
  }

The only solution to achieve this is that you need to pass the current context as a parameter. I wrote the code for only Toast but you need to modify it as per your requirements.

pass the Context from the your activity First_function(getApplicationContext()) etc..

for static string

public static String staticString = "xyz";

public static String getStaticString()
{
  return staticString;
}


String xyz = getStaticString();
查看更多
疯言疯语
3楼-- · 2019-05-12 05:46

You should have a reference to a Context. You are trying to get the application context from inside a SMS instance.

I guess you are calling the First_function from an Activity or Service. So you can do this:

Class SMS
{
    public static void First_function(Context context)
    {
        SMS sms = new SMS();
        sms.Second_function(context);
    }

    public void Second_function(Context context)
    {
        Toast.makeText(context,"Hello",1).show(); // This i anable to display and cause crash
        CallingCustomBaseAdapters();    //this was the adapter class and i anable to call this also
    }

Then, from your activity:

SMS.First_function(this); //or this.getApplicationContext() 
查看更多
登录 后发表回答