Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current context?

Tags:

android

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.

like image 458
Sudheesh Avatar asked Jan 18 '11 07:01

Sudheesh


People also ask

How do you find the current context in flutter?

An elegant solution to this problem is to use GlobalKey . That'll let you find the current BuildContext and do things with it.

How do you get the context of an application class?

Do this: In the Android Manifest file, declare the following. Now everywhere call MyApplication. getAppContext() to get your application context statically.

How do I get context from another class?

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.


2 Answers

getApplicationContext() can get the context value

like image 153
Durga Avatar answered Sep 20 '22 15:09

Durga


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

like image 23
Abandoned Cart Avatar answered Sep 21 '22 15:09

Abandoned Cart