如何从android中的静态方法调用非静态方法
我在从静态方法调用非静态方法时遇到了一个大问题。
这是我的代码
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();
您应该有一个Context的引用。 您正在尝试从SMS实例中获取应用程序上下文。
我想你是从一个活动或服务中调用First_function。 所以你可以这样做:
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 }
然后,从您的活动:
SMS.First_function(this); //or this.getApplicationContext()