Maha Mrityunjaya Saraswati Maha Mrityunjaya Saraswati - 2 months ago 12
Android Question

How to call a non-static method from one Activity to another activity

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();
}

}

Answer
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();
    }
}
Comments