Context is null android

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. 😄

Читайте также:  Как открыть андроид с компа

Источник

Keddit — Part 2: Kotlin Syntax, Null Safety and more in Android

Juan Ignacio Saravia

Feb 6, 2016 · 7 min read

Content

Part 2: Syntax, Null Safety and more…

In this Part we are going to focus on understanding some basic syntax of the language and also adding all the code that we need for the MainActivity.kt in order to open our fragment.

Kotlin Syntax

Now our MainActivity is a Kotlin file and we are ready to start learning the syntax. The first time that you see the code it may cause you a little bit of fear but believe me that you are going to love it! 😉

Kotlin is defined in m a ny ways and this is one of them (which I really like) that tries to include the most important characteristics in one sentence:

Kotlin is a Concise, Safe and Statically typed programming language focused on Interoperability with Java.

Let’s use this definition to start reviewing our generated code. I give you here both MainActivity files: Java and Kotlin files.

Concise

Did you notice that the Java file has 19 lines of code and the Kotlin file has only 12?

This is because most of the verbosity of Java was eliminated. Concise code takes less time to write and to read so this will improve your productivity.

Extend and Implement:

The words “ extends” and “ implement” were replaced by a colon “:” indifferently. In this case we are extending from AppCompatActivity (which is a Java class!)

We don’t have our classic “ public void methodName()” structure. Now we define functions inside our class with the “ fun” keyword and the return type is added to the end. But where is the type returned from our “onCreate” method?

In the case that we don’t want to return any value in Java we would use “void”, here the alternative is “Unit” which works in the same way. The compiler will know that we are not returning anything so we can omit it. In the case that we want to add it just do it in this way:

Also the parameters are in a different order. First you define the name of the variable and then the type.

In Kotlin you don’t have to put the semicolon at the end of a sentences but still you can do it if you want (don’t do it).

Values and Variable

The way to define a variable is with the “ var” keyword. The type will be inferred from the Context and the same for constants which use the “ val” keyword:

You can specify the type explicitly:

Maybe you notice that there are no primitive types, we don’t use “double” but “Double”. This is because everything in Kotlin is an object. For performance, the compiler will transform some of these objects to primitive types internally.

Properties and Fields

In Kotlin you access properties like accessing a field in Java. Instead of calling the getResources() method from an Activity you directly do:

You can still call the getResource() method but Android Studio will suggest you to change it:

It doesn’t mean that you are accessing the field directly, it’s calling the “getResource()” method but in a more convenient way.

Читайте также:  Android очистить папку другое

Safe ?: Safe!

This is one of the great things about Kotlin, everything in Kotlin is not nullable unless you specifically declare it in this way. The way to do this is with the “?” question mark which also suggest you that the value could be there or not.

With that being said, let’s see some examples:

The compiler will be checking the presence of a possible null object, this will prevent us to make the common mistake of getting a “ NullPointerException” or well known as the “Billion-dollar mistake” by Tony Hoare.

To interact with a nullable object is really easy, the “?” question mark will allow you to get the value just in case it exists, otherwise it will ignore it and you are safe to continue running the program:

If you continue playing with nullable objects maybe you end up doing this:

This is awful, but you can do this in a better way with smart cast. Just check if context is null and inside the if block the context will be considered as a non-nullable object:

This is the name used for this operator “ ?:” and you can use it to give an alternative value in case the object is null. Its like a short way to perform a null check. In this example “message” could be null, the type is “ String?”. In case the object is NOT null we’ll be sending the value of message, otherwise, the value that we provided after the elvis operator:

Statically Typed

It means that Kotlin needs to know the Type of everything that you define in the code because the compiler will do a type check during compilation. With the great support that we have in Android Studio (Thanks to JetBrains) the IDE will do a great job helping us to know if we are assigning properly a value to a variable.

Furthermore, we don’t have to specify the type when we create a variable (or a constant in this case). Checkout the toolbar constant, the type is inferred from the context and this is another great feature about Kotlin:

Type inference brings great advantages to the language: Reliability (the compiler verifies the correctness of the program), Maintainability (the code is explained by itself), Tool support (what I mentioned before, static typing enables reliable refactoring, code completion and more) and Performance (in most cases there is no need to figure out at runtime which method needs to be called).

100% Java Interoperability

This is another great feature about Kotlin, you can use Java code from a Kotlin file and vice-versa. In the Keddit App we are extending from AppCompatActivity, using the Bundle object in the onCreate method and of course using all the Android SDK to create our App :). Also, we are using other Java libraries like Retrofit, Picasso, etc.

Something really important about this is that Kotlin doesn’t have its own collections library, it relies on Java standard library classes, extending those classes with new functions. This means that you never need to convert objects between Java and Kotlin.

Updating MainActivity

I just added some methods to the MainActivity to open a fragment which will be creating in the next story and also removed some code that we don’t need in this case all related things to the menu settings.

Checkout the code to see the activity and try to understand these new concepts:

Читайте также:  Uninstall google from android

Notice how I’m using the Fragment Manager:

The new method “changeFragment()” will allow us to open a fragment inside this activity with a fade animation.

Repository

Conclusion

This is just a small part of some Kotlin concepts, we are going to continue learning more while we continue developing the Keddit App.

Источник

Context

Context – это объект, который предоставляет доступ к базовым функциям приложения: доступ к ресурсам, к файловой системе, вызов активности и т.д. Activity является подклассом Context, поэтому в коде мы можем использовать её как ИмяАктивности.this (напр. MainActivity.this), или укороченную запись this. Классы Service, Application и др. также работают с контекстом.

Доступ к контексту можно получить разными способами. Существуют такие методы как getApplicationContext(), getContext(), getBaseContext() или this, который упоминался выше, если используется в активности.

На первых порах не обязательно понимать, зачем он нужен. Достаточно помнить о методах, которые позволяют получить контекст и использовать их в случае необходимости, когда какой-нибудь метод или конструктор будет требовать объект Context в своих параметрах.

В свою очередь Context имеет свои методы, позволяющие получать доступ к ресурсам и другим объектам.

  • getAssets()
  • getResources()
  • getPackageManager()
  • getString()
  • getSharedPrefsFile()

Возьмём к примеру метод getAssets(). Ваше приложение может иметь ресурсы в папке assets вашего проекта. Чтобы получить доступ к данным ресурсам, приложение использует механизм контекста, который и отвечает доступность ресурсов для тех, кто запрашивает доступ — активность, служба и т.д. Аналогично происходит с методом getResources. Например, чтобы получить доступ к ресурсу цвета используется конструкция getResources().getColor(), которая может получить доступ к данным из файла res/colors.xml.

Таким образом, создавая, например, вторую активность, мы можем сразу обеспечить ей доступ к своим ресурсам, так как активность относится к контексту. При создании собственных компонентов View также используется контекст в конструкторах, так как компонент тоже может использовать ваши ресурсы. При создании собственных классов, если вам нужно будет обращаться к контексту, то необходимо создать конструктор:

Через контекст можно узнать практически всю информацию о вашем приложении — имя пакета, класса и т.п.

Тем не менее, следует различать контекст в разных ситуациях. Допустим, у вас есть приложение с несколькими активностями. В манифесте можно прописать используемую тему как для всего приложения, так и для каждой активности в отдельности. Соответственно, выбор контекста повлияет на результат. Как правило, при использовании собственной темы предпочтительнее использовать контекст активности, а не приложения.

Очень часто начинающие программисты впадают в ступор, когда ключевое слово this не работает в анонимных классах, например, при щелчке кнопки. В этом случае, используйте полное имя класса перед ним.

При создании адаптеров для списков также обращаются к контексту.

Или ещё пример для адаптера в фрагменте ListFragment:

Здесь тоже следует быть внимательным, если используется своя тема для списка.

Последнее замечание относится к опытным программистам. Неправильный контекст может послужить источником утечки памяти. Если вы создадите собственный класс, в котором содержится статическая переменная, обращающая к контексту активности, то система будет держать ссылку на переменную. Если активность будет закрыта, то сборщик мусора не сможет очистить память от переменной и самой неиспользуемой активности. В таких случаях лучше использовать контекст приложения через метод getApplicationContext().

ContextCompat

В библиотеки совместимости появился свой класс для контекста ContextCompat. Он может вам пригодиться, когда студия вдруг подчеркнёт метод в старом проекте и объявит его устаревшим.

Допустим, мы хотим поменять цвет текста на кнопки.

Студия ругается, что нужно использовать новый вариант getColor(int, Theme). Заменим строчку.

Если посмотреть на исходники этого варианта, то увидим, что там тоже идёт вызов нового метода. Поэтому можно сразу использовать правильный вариант, если вы пишете под Marshmallow и выше.

Источник

Оцените статью