我在静态方法中调用非静态方法时遇到了一个大问题.
这是我的代码
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
}
我能够调用Second_function但无法获取Toast和CallCustomBaseAdapter()方法,发生崩溃.
我该怎么做才能解决这个问题?
解决方法:
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
}
实现此目的的唯一解决方案是您需要将当前上下文作为参数传递.
我只为Toast编写了代码,但您需要根据自己的要求对其进行修改.
从您的活动First_function(getApplicationContext())等传递Context.
对于静态字符串
public static String staticString = "xyz";
public static String getStaticString()
{
return staticString;
}
String xyz = getStaticString();
标签:android,java,variables,android-context,static-methods
来源: https://codeday.me/bug/20190723/1511585.html