0

I am having trouble on a runtime permission method in a non-activity class. I want to call a public MainActivity method to a helper class.

MainActivity.java method:

public void a() {
    //some method
}

Now my helper class:

Class B {
    private Context mContext;
    public B(Context context) {
        this.mContext = context;
        //now I am calling Mainactivity Method
        MainActivity mainActivity = new MainActivity();
        mainActivity.a(); 
    }
}

Calling class B from CActivity:

onCreate() {
    B b = new B(this);
}

But it gives me a runtime error.

UPDATE:

My method has a runtime permission method which isn't static. Ex- requestPermissions(), onRequestPermissionsResult().

Sagar Zala
  • 4,854
  • 9
  • 34
  • 62
alien
  • 214
  • 1
  • 6
  • 12

4 Answers4

0

Make that method as static so you can call without creating the class object

eg

public static void testing() {}

now calling

MainActivity.testing();
Salman500
  • 1,213
  • 1
  • 17
  • 35
0

I don't think its a good idea to construct activity directly. If you want to signal the activity to do some task for your helper class (Class B), you better implement interfaces for listening or simply use EventBus library

If you really want to make your method work, rather than instantiating the Activity again in B class's constructor can you pass your activity as a parameter to B class? (I am not sure it would work)

Qandeel Abbassi
  • 999
  • 7
  • 31
0

You can't just put B b = new B(this); because you're instantiating another class.

Instead, use getActivity() or getContext().

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user8256287
  • 177
  • 15
0

Remove class B. and call A activity's method directly in C activity.

Extend your C activity with A activity like this:

public class C extends A{
...
}

Then in C activity call A activity's method like below:

C.super.requestAppPermissions();

Hope it will help you.

AndroidGeek
  • 399
  • 2
  • 9