如何从android中的静态方法调用非静态方法

Vis*_*hnu 3 java variables android static-methods android-context

我在静态方法中调用非静态方法时遇到了一个大问题.

这是我的代码

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
    }
Run Code Online (Sandbox Code Playgroud)

我能够调用Second_function但无法获取Toast和CallCustomBaseAdapter()方法,发生崩溃.

我该怎么做才能解决这个问题?

V.J*_*.J. 8

  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
  }
Run Code Online (Sandbox Code Playgroud)

实现此目的的唯一解决方案是您需要将当前上下文作为参数传递.我只为Toast编写了代码,但您需要根据自己的要求对其进行修改.

从您的活动First_function(getApplicationContext())等传递上下文..

对于静态字符串

public static String staticString = "xyz";

public static String getStaticString()
{
  return staticString;
}


String xyz = getStaticString();
Run Code Online (Sandbox Code Playgroud)