How to call instance method in predefined class from another class in android
I have two classes, shown below:
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
public class MYMapActivity extends MapActivity {
public static MYMapActivity ma;
public void onCreate(Bundle savedinsstate) {
super.onCreate(savedinsstate);
ma=this;
}
public void displayGo开发者_Go百科ogleMaps(){
//some code here.
}
}
From the above when I'm calling MYMapActivity.ma.displayGoogleMaps() I'mm getting NullPointerException. I have debugged the code then finally I found that in place of ma I am getting null. How can I resolve this?
You have to create an object of MYMapActivity
if you want to use it. 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()
.
You can't use "ma= this;" as a static variable outside that activity because "this" instance will be destroyed, that's why you get the NullPointerException.
In order to use displayGoogleMaps() , you have to add a static identifier to the method and call it through your class : "MYMapActivity.displacGoogleMaps();"
精彩评论