How to call a non-static method from one Activity

2020-06-17 07:49发布

问题:

I have two activities & i want to call a method clear from B. I tried like this and I am getting null pointer exceptions.

class A extends Activity {
    ...
    public void clear(){}

}

class B extends Activity{
    public void clearData() {
        A a=new A();
        a.clear();
    }        
}

回答1:

class A extends Activity{
static A instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    instance = this;
}

public static A getInstance() {
    return instance;
}
....
public void clear(){}

}

and in class B:

class B extends Activity {
  public void  clearData(){
      A a = A.getInstance();
      a.clear();
    }
}