I don\'t really get the idea behind how this whole thing works really, so if I have some class A
that need the context of a class B
which extends <
In Kotlin will be :
activity?.applicationContext?.let {
it//<- you context
}
you pass the context to class B in it's constructor, and make sure you pass getApplicationContext() instead of a activityContext()
The best and easy way to get the activity context is putting .this
after the name of the Activity. For example: If your Activity's name is SecondActivity
, its context will be SecondActivity.this
If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.
But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Application
class, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Application
instead.
I'd suggest reading this article about context to better figure it out what context you need.
You can create a constructor using parameter Context of class A then you can use this context.
Context c;
A(Context context){ this.c=context }
From B activity you create a object of class A using this constructor and passing getApplicationContext().
Ok, I will give a small example on how to do what you ask
public class ClassB extends Activity
{
ClassA A1 = new ClassA(this); // for activity context
ClassA A2 = new ClassA(getApplicationContext()); // for application context.
}