Brandon
Brandon

Reputation: 1886

Can I and should I pass a Context to a static method outside of the UI?

I've looked around but never found a straightforward answer to this question. I'm wondering what would happen if I use a pattern that requires me to pass a Context to static methods to do things on the backend. For instance:

public static Observable<CreateThing> createNewThing(String thingName, Context context) { // Passing Context in
    return RestNetworker.handleResponse(ServiceGenerator.createService(Service.class).createThing(thingName))
            .doOnNext(response -> DatabaseHelper.getInstance(context).createThing(new Thing(response.getThingId(), thingName))); // context used to get instance of DatabaseHelper
}

This method makes an API call and then writes the object to the database locally after a success response. However, I need to pass a Context to create the instance of the database helper. I could alternatively pass the database helper itself, but then I'd be creating the instance (rather getting it, since it's singleton) in the Activity code and I'd rather not do that either.

My question really is: If, say, a user exits the Activity while the API call is in progress, will this Context instance get GC'd and result in an NPE when the response comes back? I've done this kind of thing before and never noticed that issue, but it really seems that there should be some consequence of doing this. I know that other developers must do some things off the UI thread that require a Context, so this should be a relatively easy question to answer.

Thanks guys! Please let me know if you need any more information to provide better context. Heh.

Upvotes: 0

Views: 165

Answers (1)

Steve M
Steve M

Reputation: 9784

The rule is that you do not pass an instance of the Activity to some object that may keep a reference to it outside of the lifecycle of the Activity. This will cause a memory leak, as the GC will not be able to free the memory allocated to the Activity and the entire view tree contained within. In those instances you pass getApplicationContext().

In cases where the context will only be referenced for the duration of the method call, passing the Activity as this is fine.

In your case, it seems like DatabaseHelper may store a reference to the context, so I would use getApplicationContext() Note that you would not get NPE because the reference was GC if you passed an Activity, that doesn't make sense - if the DatabaseHelper was storing a strong reference, this could not occur (at least on the reference to the Activity itself).

Upvotes: 2

Related Questions