- Different ways to get Context in Android
- The “this” Keyword
- Get current activity context : View.getContext()
- Get App-level context : getApplicationContext()
- Get Original context : getBaseContext()
- Get Context from Fragment : getContext()
- Get parent Activity : getActivity()
- Non-nullable Context : requireContext() and requireActivity()
- Context в Android приложении
- Что такое Context?
- Контекст приложения
- Контекст Activity
- getContext() в ContentProvider
- Когда нельзя использовать getApplicationContext()?
- Правило большого пальца
- Context — контекст в android — что это, как получить и зачем использовать
- Getting Android’s context for unit testing #134
- Comments
- jmiecz commented May 30, 2018
- arnaudgiuliani commented May 31, 2018
- jmiecz commented May 31, 2018
- arnaudgiuliani commented Jun 1, 2018
- jmiecz commented Jun 1, 2018 •
- arnaudgiuliani commented Jun 4, 2018
- qbait commented Aug 16, 2018 •
- qbait commented Aug 17, 2018
- arnaudgiuliani commented Aug 20, 2018
- qbait commented Aug 20, 2018
- arnaudgiuliani commented Aug 20, 2018
- NurseyitTursunkulov commented May 19, 2019
- jasofalcon commented May 16, 2021
- Get context of test project in Android junit test case
- 11 Answers 11
Different ways to get Context in Android
Context is one of the important and most used property. You need Context to perform a lot of things on Android. Be is displaying a toast or Accessing database, you use context a lot while building Android app.
Context is property, well, which can give you the context of whats happening on the Screen/Activity it belongs to. It contains information about what Views are there, How they are laid out etc.
So, it is important to know different types of Context and methods you can call to get context. Lets get started.
The “this” Keyword
The this keyword in general sense refers to current class instance. So, when use “this” keyword inside an Activity, it refers to that Activity instance. And as Activity is subclass of “Context”, you will get context of that activity.
If you are not directly inside Activity, for example inside an OnClickListener, you can get the current context by referencing with Activity name like MainActivity.this (Java) or this@MainActivity (Kotlin)
Get current activity context : View.getContext()
This method can be called on a View like textView.getContext() . This will give the context of activity in which the view is currently hosted in.
Get App-level context : getApplicationContext()
If you need to access resources which are out of scope of specific activity, like when accessing SharedPreferences, displaying Toast message etc. you can use this.
So unlike activity context, which will be destroyed when close an activity, Application Context the application wide context which won’t get destroyed until you completely close application.
You can directly access application context by calling getApplicationContext() or by calling on activity context like context.getApplicationContext()
Get Original context : getBaseContext()
This method is only useful when you are using ContextWrapper. You can get the original context which was wrapped by ContextWrapper by calling contextWrapper.getBaseContext()
( ContextWrapper is a wrapper class, using which you can override any method of Context, while still retaining the original context)
Get Context from Fragment : getContext()
When you call getContext() from an Fragment, you will get the context of the activity in which that fragment is hosted in.
Get parent Activity : getActivity()
You can get the parent activity from a Fragment by calling getActivity() .
💡Difference : Both getContext() and getActivity() are not much different in most cases, when you just need a context as both will get Parent activity context. Except for some cases, for example when using ContextWrapper, getContext() and getActivity() can point to different contexts.
Non-nullable Context : requireContext() and requireActivity()
These methods are same but “NotNull” versions of getContext() and getActivity() respectively. Usually, if a fragment is detached from Activity, you will get “null” value when you call getContext() or getActivity() . So even when you are sure the context won’t be null, you still have to add null checks (especially in Kotlin) because they return Nullable type.
But requireContext() and requireActivity() will throw IllegalStateException instead of returning null, if there is no context.
These methods are mainly useful when you using Kotlin and you need a Non-Nullable Context. So using these methods instead, is matter of personal preference.
So, did you learn something new? If you did, please clap and share the post. 😄
Источник
Context в Android приложении
Что такое Context?
Как следует из названия, это контекст текущего состояния приложения или объекта. Это позволяет вновь созданным объектам понять, что вообще происходит. Обычно его вызывают, чтобы получить информацию о другой части программы.
Кроме того, Context является проводником в систему, он может предоставлять ресурсы, получать доступ к базам данных, преференсам и т.д. Ещё в Android приложениях есть Activity . Это похоже на проводник в среду, в которой выполняется ваше приложение. Объект Activity наследует объект Context . Он позволяет получить доступ к конкретным ресурсам и информации о среде приложения.
Context присутствует практически повсюду в Android приложении и является самой важной его частью, поэтому необходимо понимать, как правильно его использовать.
Неправильное использование Context может легко привести к утечкам памяти в Android приложении.
Существует много разных типов контекста, поэтому давайте разберёмся, что каждый из них представляет из себя, как и когда их правильно использовать.
Контекст приложения
Это singleton-экземпляр (единственный на всё приложение), и к нему можно получить доступ через функцию getApplicationContext() . Этот контекст привязан к жизненному циклу приложения. Контекст приложения может использоваться там, где вам нужен контекст, жизненный цикл которого не связан с текущим контекстом или когда вам нужно передать контекст за пределы Activity .
Например, если вам нужно создать singleton-объект для вашего приложения, и этому объекту нужен какой-нибудь контекст, всегда используйте контекст приложения.
Если вы передадите контекст Activity в этом случае, это приведет к утечке памяти, так как singleton-объект сохранит ссылку на Activity и она не будет уничтожена сборщиком мусора, когда это потребуется.
В случае, когда вам нужно инициализировать какую-либо библиотеку в Activity , всегда передавайте контекст приложения, а не контекст Activity .
Таким образом, getApplicationContext() нужно использовать тогда, когда известно, что вам нужен контекст для чего-то, что может жить дольше, чем любой другой контекст, который есть в вашем распоряжении.
Контекст Activity
Этот контекст доступен в Activity и привязан к её жизненному циклу. Контекст Activity следует использовать, когда вы передаете контекст в рамках Activity или вам нужен контекст, жизненный цикл которого привязан к текущему контексту.
getContext() в ContentProvider
Этот контекст является контекстом приложения и может использоваться аналогично контексту приложения. К нему можно получить доступ через метод getContext() .
Когда нельзя использовать getApplicationContext()?
Правило большого пальца
В большинстве случаев используйте контекст, доступный непосредственно из компонента, в котором вы работаете в данный момент. Вы можете безопасно хранить ссылку на него, если она не выходит за пределы жизненного цикла этого компонента. Как только вам нужно сохранить ссылку на контекст в объекте, который живет за пределами вашей Activity или другого компонента, даже временно, используйте ссылку на контекст приложения.
Источник
Context — контекст в android — что это, как получить и зачем использовать
Контекст (Context) – это базовый абстрактный класс, реализация которого обеспечивается системой Android. Этот класс имеет методы для доступа к специфичным для конкретного приложения ресурсам и классам и служит для выполнения операций на уровне приложения, таких, как запуск активностей, отправка широковещательных сообщений, получение намерений и прочее. От класса Context наследуются такие крупные и важные классы, как Application, Activity и Service, поэтому все его методы доступны из этих классов.
Получить контекст внутри кода можно одним из следующих методов:
- getBaseContext(получить ссылку на базовый контекст)
- getApplicationContext(получить ссылку на объект приложения)
- getContext (внутри активности или сервиса получить ссылку на этот объект)
- this(то же, что и getContext)
- MainActivity.this (внутри вложенного класса или метода получить ссылку на объект MainActivity)
- getActivity(внутри фрагмента получить ссылку на объект родительской активности)
Контекст (Context) – это базовый абстрактный класс, реализация которого обеспечивается системой Android. Этот класс имеет методы для доступа к специфичным для конкретного приложения ресурсам и классам и служит для выполнения операций на уровне приложения, таких, как запуск активностей, отправка широковещательных сообщений, получение намерений и прочее. От класса Context наследуются такие крупные и важные классы, как Application, Activity и Service, поэтому все его методы доступны из этих классов. Источник
Получить контекст внутри кода можно одним из следующих методов:
Источник
Getting Android’s context for unit testing #134
Comments
jmiecz commented May 30, 2018
Is there a way to get either the Android’s context or resources to use for a unit test? The use case is, having a json file we can reference vs hard coding the json string into the class we are unit testing.
The text was updated successfully, but these errors were encountered:
arnaudgiuliani commented May 31, 2018
with Junit and Mockito we can’t recreate a «real» Android context. You can use more easily make such thing in Android instrumented tests.
I can be interesting to investigate with new nitrogen project, or more about Robolectric project if we can do something.
jmiecz commented May 31, 2018
If I were to use Robolectric, I know they offer a way to grab the context, how can I pass it to one of my modules?
arnaudgiuliani commented Jun 1, 2018
If you want to add/override the existing definition of Application , you just have to provide a module like:
And then use the androidContextModule in the list of modules that you use, at the end of the list of modules: startKoin(listOf(module1, . androidContextModule))
Do we have a direct function to create an Android context with Robotlectric?
jmiecz commented Jun 1, 2018 •
Hello @arnaudgiuliani, Below is a sample unit test using what you suggested and having success on accessing the resources! Please let me know if there is anything else I can do to help.
arnaudgiuliani commented Jun 4, 2018
Great 👍
A sample/geetting started project will gather test samples for Android. I keep you in touch!
qbait commented Aug 16, 2018 •
Unfortunately, I still have a problem with configuring robolectric and koin. I’m getting the following error
I’ve also copy and paste @jmiecz code and tried on @arnaudgiuliani koin’s sample app with the same results.
qbait commented Aug 17, 2018
In the end it works. I use version 1.0.0-beta-6
I don’t have any @Before and @After nor specific modules for tests. Is my configuration alright or it works by accident? 🙂
arnaudgiuliani commented Aug 20, 2018
Nop. For an instrumented test, your Koin container is already started via your startKoin() .
qbait commented Aug 20, 2018
What do you mean by instrumented tests @arnaudgiuliani ?
My tests are under test folder and run on jvm. Are they still called instrumented because of Robolectric
arnaudgiuliani commented Aug 20, 2018
Yes kindof. This is unit test, with Android instrumented classes.
NurseyitTursunkulov commented May 19, 2019
If you want to add/override the existing definition of Application , you just have to provide a module like:
And then use the androidContextModule in the list of modules that you use, at the end of the list of modules: startKoin(listOf(module1, . androidContextModule))
Do we have a direct function to create an Android context with Robotlectric?
where to put it?
jasofalcon commented May 16, 2021
applicationContext < >doesnt seem to exist anymore, is there a working github example with latest koin?
Источник
Get context of test project in Android junit test case
Does anyone know how can you get the context of the Test project in Android junit test case (extends AndroidTestCase).
Note: The test is NOT instrumentation test.
Note 2: I need the context of the test project, not the context of the actual application that is tested.
I need this to load some files from assets from the test project.
11 Answers 11
There’s new approach with Android Testing Support Library (currently androidx.test:runner:1.1.1 ). Kotlin updated example:
If you want also app context run:
After some research the only working solution seems to be the one yorkw pointed out already. You’d have to extend InstrumentationTestCase and then you can access your test application’s context using getInstrumentation().getContext() — here is a brief code snippet using the above suggestions:
As you can read in the AndroidTestCase source code, the getTestContext() method is hidden.
You can bypass the @hide annotation using reflection.
Just add the following method in your AndroidTestCase :
Then call getTestContext() any time you want. 🙂
If you want to get the context with Kotlin and Mockito, you can do it in the following way:
Update: AndroidTestCase This class was deprecated in API level 24. Use InstrumentationRegistry instead. New tests should be written using the Android Testing Support Library. Link to announcement
You should extend from AndroidTestCase instead of TestCase.
AndroidTestCase Class Overview
Extend this if you need to access Resources or other things that depend on Activity Context.
Источник