[英]How to call instance method in predefined class from another class in android
I have two classes, shown below: 我有两个类,如下所示:
TestActivity.java TestActivity.java
public class TextActivity extends Activity {
public void onCreate(Bundle savedinsstate) {
super.onCreate(savedinsstate);
Intent intent=new Intent(this,MYMapActivity.class);
startActivity(intent);
MYMapActivity.ma.displayGoogleMaps();
}
}
MYMapActivity.java MYMapActivity.java
public class MYMapActivity extends MapActivity {
public static MYMapActivity ma;
public void onCreate(Bundle savedinsstate) {
super.onCreate(savedinsstate);
ma=this;
}
public void displayGoogleMaps(){
//some code here.
}
}
From the above when I'm calling MYMapActivity.ma.displayGoogleMaps() I'mm getting NullPointerException. 从上面的内容中,当我调用MYMapActivity.ma.displayGoogleMaps()时,我得到了NullPointerException。 I have debugged the code then finally I found that in place of ma I am getting null.
我已经调试了代码,然后最终我发现代替ma我得到的是null。 How can I resolve this?
我该如何解决?
You can't use "ma= this;" 您不能使用“ ma = this;” as a static variable outside that activity because "this" instance will be destroyed, that's why you get the NullPointerException.
作为该活动之外的静态变量,因为“ this”实例将被销毁,这就是为什么您得到NullPointerException的原因。
In order to use displayGoogleMaps() , you have to add a static identifier to the method and call it through your class : "MYMapActivity.displacGoogleMaps();" 为了使用displayGoogleMaps(),您必须向该方法添加静态标识符,并通过您的类进行调用:“ MYMapActivity.displacGoogleMaps();”
You have to create an object of MYMapActivity
if you want to use it. 如果要使用
MYMapActivity
对象,则必须创建它。 Static fields need to be initialized, too. 静态字段也需要初始化。
public static MYMapActivity ma = new MYMapActivity();
or make all methods static. 或将所有方法设为静态。 If you don't need object from the class.
如果您不需要类中的对象。 Then you can call
MYMapActivity.displacGoogleMaps()
. 然后,您可以调用
MYMapActivity.displacGoogleMaps()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.