I want to use it in my array adapter. When I put this
in a sub-activity to create an adapter it does not work.
An elegant solution to this problem is to use GlobalKey . That'll let you find the current BuildContext and do things with it.
Do this: In the Android Manifest file, declare the following. Now everywhere call MyApplication. getAppContext() to get your application context statically.
In an android Application, is there any way to get the context in android in a non-activity class if the activity class name is known? pass the context of ur current activity to the java class constructor... If your non-activity class is a Fragment , see stackoverflow.com/questions/8215308/using-context-in-a-fragment.
getApplicationContext()
can get the context value
You can get context a few ways:
By the Activity, using Your_Activity_Name.this
By the application, using getApplicationContext()
By the View, using Your_View.getContext()
The only one I would not recommend is using getBaseContext()
. If you need something universal, have a public static variable in your main activity and assign the application context to it when your app starts. This way you can always call Your_Activity.your_context_variable
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