简体   繁体   中英

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 displayGoogleMaps(){
    //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 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();"

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM