Java android context this

In android, when is a context different from «this»?

I am at baby step level of programming on Android (and in Java in general). I do understand that Activity inherits from the Context class. However in every code snippet I have come across, every time a context must be mentionned, it is set to «this». My question is : when is a context different from «this» ? Could you provide an real life example of context needing to be different from «this»? Thank you very much.

5 Answers 5

Typically, you will want to use this when you are «inside» of an Activity. However, when you are using for example a Helper class, the reference this will not work. An example can be something like this:

public class MyActivity extends Activity < @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); >> 

The above code locks the orientation to the current orientation. Notice that you need to supply the method with an Activity parameter, since you cannot use:

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); 

In the first example, you could use this to achieve this, because you were «inside» of an Activity.

Another type of example, how do you set onClickListener .

First example, when you use this :

public class MyActivity extends Activity implements View.OnClickListener < @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); Button btn=(Button)findViewById(R.id.mybutton); btn.setOnClickListener(this); >@Override public void onClick(View v) < //handle the click event >> 

In this example, you can use this because in the first line, we wrote implements View.OnClickListener , so the class inherits from the given interface. Without the implements thingie, you couldn’t do it. An example of setting the onClickListener without this :

public class MyActivity extends Activity < @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); Button btn=(Button)findViewById(R.id.mybutton); btn.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < //handle the click event >>); > > 

In the second example, we are defining an Anonymous Inner Class , which will handle the click event of the button. Notice that in this case, our Activity does NOT implements View.OnClickListener .

Читайте также:  Системы защиты питон противоугонное устройство

Источник

What’s meant by the «this» context?

I have looked at a lot of android tutorials over the internet. In these tutorials they use the this context for the context everywhere. I know what this keyword means in Java, but I can’t make equal this, with the this keyword in Android programming. For example, at AlertDialog.Builder , on the developer.android.com site, there is only one reference at the parameters to the Context, but I can’t learn what this this means here.

6 Answers 6

if you have an Activity you can use this because:

  • this is the current instance of a class
  • an Activity is inherits from the class «Context»

so you can use your current Activity as a Context.

Look here for the Acitivty doc

and here for an explanation of this

If you know «this» variable.. then u may also know that it holds reference for the current object.. so if some method asks for a Context object you can pass this variable only when it extends classes like Context or Activity.. Because Activity implements context so obeviously its a Context

Context of current class is called This in Android.

Here is another question where they explain Context . As activities and services extend Context , the this context is a reference to this activity or service.

The keyword this is simply a reference — within an instance of a class — to itself.

There are two common uses of «this» in Android. These aren’t particular to Android, but are valid in Java in general.

  1. this.getResources() says to call the getResources() method on this instance. The this portion of it is usually unnecessary and used implicitly.
  2. Foo.this.getResources() could be called from an inner class. This could be handy if the inner class defines getResources() also, but you want the version defined in the other class.

this is a reference to the current object

You can use this to refer to any current instance and any instance of its super class.

If your class extends Activity. It is a case of inheritance. your class is subclass and Activity class is parent class. then you can use this keyword to get instance of Activity beacause Activity class is super class of your class. This is implicit casting

also Activity class Context as superclass. so you can refer the instance of that class using this keyword.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Context в Android приложении

Context в Android приложении

Как следует из названия, это контекст текущего состояния приложения или объекта. Это позволяет вновь созданным объектам понять, что вообще происходит. Обычно его вызывают, чтобы получить информацию о другой части программы.

Кроме того, 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 . Некоторые вещи, которые вы попытаетесь сделать с этим контекстом, потерпят неудачу, в основном связанные с графическим интерфейсом.
  • Могут появляться утечки памяти, если контекст из getApplicationContext() удерживается на каком-то объекте, который вы не очищаете впоследствии. Если же где-то удерживается контекст Activity , то как только Activity уничтожается сборщиком мусора, всё остальное тоже уничтожается. Объект Application остается на всю жизнь вашего процесса.

Правило большого пальца

В большинстве случаев используйте контекст, доступный непосредственно из компонента, в котором вы работаете в данный момент. Вы можете безопасно хранить ссылку на него, если она не выходит за пределы жизненного цикла этого компонента. Как только вам нужно сохранить ссылку на контекст в объекте, который живет за пределами вашей Activity или другого компонента, даже временно, используйте ссылку на контекст приложения.

Источник

Различие между context и this

В андроиде есть context -ссылка, а на самой джаве есть this -ссылка. Так вот в чем разница контекста от зиса и можноли пример с контекстом а то я запутался в нем. Благодарю.

1 ответ 1

this и Context – это принципиально разные вещи.

this – это ключевое слово языка Java. this – это ссылка на самого себя. Ссылка на объект, для которого был вызван метод.

Context (в android) – это абстрактный класс, предоставляющий методы для доступа к т.н. глобальной информации (к ресурсам, классам, для управления активити, сервисами и так далее).

Непосредственными субклассами классами Context являются классы ContextWrapper и MockContext . В свою очередь, прямыми субклассами класса ContextWrapper , в том числе, являются классы Application и Service , а непрямым – класс Activity .

 getActivity().runOnUiThread(new Runnable() < @Override public void run() < // some actions >>); 

Здесь, для запуска кода в UI -потоке используется объект класса Activity (который является (непрямым) наследником класса Context ).

Еще один пример с Context :

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); 

Здесь в конструктор класса LinearLayoutManager передается объект класса Activity . Такой вызов, возможен, например, из фрагмента.

Из самой активити можно напрямую вызвать:

LinearLayoutManager layoutManager = new LinearLayoutManager(this); 

так как this в методах активити является как раз объектом класса Activity .

Источник

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