android 静态方法调用方法调用方法调用,java – 如何从android中的静态方法调用非静态方法...

在Android编程中,遇到在静态方法里调用非静态方法导致崩溃的问题。解决方法是将当前上下文作为参数传递给静态方法。通过修改`First_function`,传入`ApplicationContext`,然后在`Second_function`中使用这个上下文来创建`Toast`,避免了错误。这同样适用于其他需要上下文的方法调用,如自定义适配器。
摘要由CSDN通过智能技术生成

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

这是我的代码

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值