0

I create methodAbc() for getting network information. Context is required in this method. I want to use this method for 3 Activities.

How can I implement it?

Michael Yaworski
  • 13,049
  • 19
  • 64
  • 94
user3153149
  • 83
  • 1
  • 1
  • 6

3 Answers3

5

There is two option right now i can see.

  1. Create a BaseActivity which will consist the method .. all the activities will extend from BaseActivity
  2. Simply create a Util static method passing a Context as parameter
stinepike
  • 52,673
  • 14
  • 90
  • 109
2

You can always access a public method from any class. You just have to create an instance of that class, and then call the method on that instance. For example:

public void methodAbc(Context c) {
    // do stuff
}

and then reference that method like so:

YourClass x = new YourClass(yourClassParameters);
x.methodAbc(yourContext); // yourContext might be getApplicationContext()

That, or you could make the method static. Although, you may not be able to make your method static if it has calls to other non-static class methods. Assuming that it can be made a static method, though:

public static void methodAbc(Context c) {    
    // do stuff
}

and then you can call it from another class, like this:

YourClass.methodAbc(yourContext); // yourContext might be getApplicationContext()
Michael Yaworski
  • 13,049
  • 19
  • 64
  • 94
-2
public void myMethod(Context context) {
//etc etc
}

Now from any class just refer to it as MyClass.myMethod(this);

Ogen
  • 6,396
  • 5
  • 46
  • 119