0

I normally do Windows/C#/C++ programming but I dabble in Android so I've been asked to look at Android program to fix a bug in it. I do not have a mandate to re-architect it, so what's static stays static.

The problem is this: In one Activity it has a public static method. It also has all the usual non-static methods. There's one instance of this particular Activity class.

I want to be able to call some non-static methods on this Activity class and access some of its data from the static method. Obviously if I try to do so directly I get,

Cannot make a static reference to the non-static method ...

I assume there must be a way to stash some reference to that specific instance of Activity class in some global public place during the onStart() or onCreate() methods using this or some context, and then use that in the static method to make the calls, e.g.,

myStoredClassInstance.aNonStaticMethod();

...but I don't know the syntax. Can anyone help me out on this?

PS Before you say this is a duplicate of this: calling non-static method in static method in Java note that that question is about calling a non-static method of a separate class, so the answers involved creating a new instance of that class on the fly. In my case I want to know the syntax of accessing an existing specific class.

Community
  • 1
  • 1
user316117
  • 7,971
  • 20
  • 83
  • 158
  • "I assume there must be a way to stash some reference to that specific instance of Activity class in some global public place" -- only if you like memory leaks and buggy code. "I want to be able to call some non-static methods on this Activity class and access some of its data from the static method" -- the caller should pass in the `Activity` as a parameter, since somebody decided not to make the method be non-`static`. "Before you say this is a duplicate of this" -- it is a duplicate, because your scenario is no different than the linked-to question. – CommonsWare May 16 '14 at 21:05
  • ... except the proposed solutions don't apply to my question. So if someone was looking for an answer to my question then following that link wouldn't help them. In any case I have a solution which works for me, so I'll post it if someone doesn't first. – user316117 May 16 '14 at 21:34

1 Answers1

0

This seemed to work for me

Create a class member...

private static MyActivity myActivityClassInstance = null;

in onCreate() . . .

myActivityClassInstance = this;

In the static method of the same class . . .

if (myActivityClassInstance != null)  {
    myActivityClassInstance.myNonStaticMethod();
}

I wrapped it in a test for null because it could potentially get called before onCreate() is called. On the other hand onCreate() just happens to be the first thing that happens in the program that I've been asked to tinker with. There are probably better places to put this if you have more control over your project.

user316117
  • 7,971
  • 20
  • 83
  • 158