ibrahim
ibrahim

Reputation: 653

Getting activity context without instantiating it?

I have been struggling with this problem for two days,I am in situation where i need to use a method in ActivityB from ActivityA . The problems lays in getting the context of A i have tried many solutions like:

static ActivityA activityA;

In onCreate state:

activityA = this;

and add this method:

public static ActivityA getInstance(){
   return   activityA;
}

In ActivityB, call

ActivityA.getInstance().myFunction(); //call myFunction using activityA

it did not work out because this need the ActivityA to be instantiated in order to pass its context to A but this is not accomplishable in my case is there any way of getting an activity's context without switching activities . my question might turn out to be simple or intuitive but im new to this concept , thanks in advance

Upvotes: 0

Views: 151

Answers (4)

Prathamesh Toradmal
Prathamesh Toradmal

Reputation: 299

As you want to have common functionality in both activities, you can create BaseActivity that extends Activity and define your method in that and extend ActivityA and ActivityB by BaseActivity then you can access methods. You can do it like this,

public class BaseActivity extends Activity
{
  public void myFunction()
 {
  ...
 }
}

And do this for other activities:

public class ActivityA extends BaseActivity
{
 public void someMethod()
 {
   myFunction();   // you can call function here directly
 }
}

Upvotes: 1

BhanuSingh
BhanuSingh

Reputation: 126

There are two options:

1) Add the static keyword to your shared methods

OR

2) You can try reflection.

For reference follow the link: What is reflection and why is it useful?

Upvotes: 0

Chetan Joshi
Chetan Joshi

Reputation: 5711

Here I Created Two Classes Consider as Activities , And Then Created one Public methodA() in class Activity_A , then Created Class Activity_B and Created methodB() , And Created Object of Activity_A and Called methodA() by passing context of Activity Activity_B .

        class Activity_A{
            public void methodA(Context context){
                Toast.makeText(context,"methodA",Toast.LENGTH_LONG).show();
            }
        }

        class Activity_B{
            public void methodB(){
                Activity_A activity_a = new Activity_A();
                activity_a.methodA(Activity_B.this);
            }
        }

Upvotes: 0

g7pro
g7pro

Reputation: 827

You could extent class A using Class B simply

OR

public static ActivityA activityA;

In onCreate state:

{
activityA = this;
}

Outside Oncreate

public myFunction{
}

and in ActivityB call

activityA.myFunction();

Upvotes: 0

Related Questions