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.
There is no way to pass the context to the target activity using Intent.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With