Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Activity Context to constructors to use internally - is this bad

Tags:

Is it bad practice to pass the Context to a constructor and save it as a private variable for internal use? The other option is to pass the Context as a parameter to methods that need it.

Which is a better option? I have a feeling that passing to the constructor might result in memory leaks accidentally.

like image 290
jax Avatar asked May 26 '10 15:05

jax


People also ask

Can application context be passed using intent to another activity?

There is no way to pass the context to the target activity using Intent.

What context is the keyword this android?

What is "this" ? It is a keyword that refers to the current object in a method or constructor. It is used both in Java and Kotlin. The most common use of the "this" keyword is to eliminate the confusion between class attributes and parameters with the same name as a property in a class.

How do you pass activity context?

You can get the context by invoking getApplicationContext() , getContext() , getBaseContext() or this (when in the activity class). Context is tied with lifecycle of its activity/application and commonly used for creating new objects, accessing resources e.t.c.


1 Answers

Often, all you need is the ApplicationContext, so what you can do is pass this.getApplicationContext() instead of just this. Your app context exists for the lifetime of the app anyway, so it's not a memory leak.

like image 187
JRL Avatar answered Sep 19 '22 20:09

JRL