6

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();
    }        
}
2
  • Just create an AppActivity, and extend it in your both the activities A and B. Now place this function in this new activity. Its easily accessible to you. Sep 14, 2016 at 11:40
  • You cannot create a new object of your activity class , just get the current instance of the A Activity and call clear() on that instance Sep 14, 2016 at 11:41

1 Answer 1

21
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();
    }
}
5
  • 2
    Nice solution, I didn't know that non-static methods can be called like this. I don't know why people downvote such answers. Jan 17, 2019 at 9:10
  • You have made it as static, So in future will be any memory leak in heap or PermGem memory? Sep 25, 2019 at 6:23
  • 1
    @MadhusudhanAradya yes, there will definitely be memory leaks, as the static variable will hold onto Activity context, even when Activity no longer exists. It was the best solution I could come up at that time. I will be updating this answer in the future with more efficient solutions for sure. Sep 25, 2019 at 6:28
  • @Aman Grover is there any optimized solution for calling the function without making it static Sep 25, 2019 at 6:30
  • @MadhusudhanAradya you can make your own listeners, which are basically interfaces, to call a method from another activity. Sep 25, 2019 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.