Manually setting context in Android - android

I am new to Android development and I made a research about Context. I understand what it is and why is usefull. But I see that android handles context for me in activities for example, I have to extends a class that inherits from context and thats it. However in some situations I have to manually add context to a thing. For example when creating a new instance of a view from kotlin. I have to pass a context to the view constructor, for example: Button(this)
Why do I have to tell a view instance that it is part of an activity explicitly?
I am defining it inside the activity after all.
I understand that context it's like a bridge between my app and external resources and system tools but setting it manually sometimes confuses me.

True, theoretically, that could have been done only when attaching the view to a parent, and then if the parent is attached to the activity root it has context, if not - when attaching a view, Android could have gone over its descendants and set their Context.
However:
It is inconvenient to implement. It's easy to have autonomous views with each already set to its context.
There are some things that are in the context and are necessary for manipulating the view. E.g. constraint system, metrics... many bits and bolts. Views also listen to events and can provide some services that require Context before they are attached to another view.
What if you have several contexts. You want to be able to choose which context to refer to. Say, you got an always-on-too floating button that is managed by some service and views managed by the activity.
It is highly recommended to peek in Android sources. You will find cool facts inside, and it's an excellent way to learn.

I found this article: https://www.101apps.co.za/index.php/articles/all-about-using-android-s-context-class.html
I think that explains very well why do we need to pass context manually to view instances.
"Passing the context to the view when it is being constructed, gives
you the flexibility to use a different context to construct the view,
as the one used by the activity, for example. This gives the view
access to resources other than those used by the activity."
Android could set context automatically but it gives you freedom to choose another one. That could be useful.

This is because there can many other parameters for this.
We set the context because we let the Button base class(or any other you're using) that the declared variable is instance of Button but not the other classes available all over!

Related

How do I learn which Context I have to use for each situation in Android?

I'm learning Kotlin and I've already had to fill the context several times in different ways, like this, context.application, requireContext() etc.
I'm wondering if there is any way I can realize which context to use by myself instead copying them with tutorials.
There are mainly two type of context in android & both of them are provided to you as a ContextWrapper class object.
Application Context
This context is basically provided/used when you need to do some work that doesn't involves any view/UI operation (where you don't need to refer to/rely on any UI code).
This is mostly helpful when you're doing operations directly via your process that doesn't need any UI interactions like for an example, getting list of contacts via content provider.
So, you can consider this as parent of all other context you can have in your application and apparently this is consistent for your given process.
This context is retrieved via Application class of your app, or via any other activity by requesting like (activity.applicationContext).
Activity Context
This context is basically bounded/limited to given activity you're in right now. This is helpful to mainly do UI operations because, your context is part of the same UI you are in right now.
So, yes you can consider this a child context that can changes as per your activity changes. For most of the cases, it is not preferred to store & share this context across UI/Activities as it can lead to memory leaks.
This context can be retrieved once you're on any activity class via (Activity.this, this, context in fragments & custom views)
I agree personally that context has been confusing topic on Android since the beginning, but if you know C/C++ then I can relate this to 'pointers' (conceptually). Context are pointers for given activity/application class.

Why we need to pass Context to a View?

Each Activity is a Context.
Each View needs a Context.
Is it correct to say that when we pass the Context to a View, we are basically adding a View to a certain Activity by passing the Context?
The context is required because it provides access to many android system resources.
It provides theme information so that the view can properly draw itself with the given theme, but also provides a way to access other types of resource.
It provides access to layout inflater which may be needed to create child views.
You can use context to access String resources (and other resources). You may need Strings to add an appropriate text label to your view.
If you need access to shared preferences, that can be accessed via a context.
It is not correct to say that you are adding a view to an activity if you have passed that activity to the view as a context. The activity is simply providing the context needed by the view.
Here is a more thorough answer explaining the purpose of a context

How many types of context in android and what is better to use

I just wanted to know how many ways to get the context, which method used in which situation.
Which one better to use, and what is the main and key deference between them.
For Your better understands you should read android official blog. an also look at HackBod Answer.
There are some references URL which help you more about the context
What exactly does using the Application Context mean?
Difference between Activity Context and Application Context
http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html
Thanks
Context class represents the local environment of an App, It encapsulates all the services and resources available to the app. There is a base class ApplicationContext, and sub classes for components: Activity, Service etc.
Always prefer using ApplicationContext because it is global and doesn't cause serious issues if its leaked, that is: an unused reference of it stays and is not garbage collected.
Sometimes you have to use sub components like Activity or Service as context. Use this when creating Intents, or creating UI Elements, or showing a toast etc. That is: functions that are specifically bound to these component's identity, its UI or its display window.

When will a View method's Context param not be equivalent to .getContext()

If you are able to call view.getContext() to return the Activity's context under which the view instance is currently being rendered, why do some of the View family methods take a Context as a parameter?
Could this not be implicit, or are there occassions when getContext() is different from a Context passed to one of these methods?
Here is an example: http://developer.android.com/reference/android/widget/ViewAnimator.html#setInAnimation(android.content.Context, int)
Many thanks for clearing this up
view.getContext() actually return's your Activity's context, not application's. That is the reason you need to provide such context when initializing a new View.
And there's a difference between these two contexts. An Activity's context is attached to that particular activity's life-cycle. However, the application's context is referring to application's life-cycle.
For more info, read this.
I recently read some API returning IBinder, like getWindowToken() and getApplicationWindowToken(). Quoting the latter:
Retrieve a unique token identifying the top-level "real" window of the
window that this view is attached to. That is, this is like
getWindowToken(), except if the window this view in is a panel window
(attached to another containing window), then the token of the
containing window is returned instead.
Maybe this IPC mechanism has something to do with the View API. Android designers are not stupid or zealous: if they require a Context to build a View, it means that a Context is all they need, so building a View must be possible with an application context, a service context and -of course!- an activity context, but an activity is not required. The Context is just an umbrella API to retrieve resources, accessing databases, building intents and the like.
This is not the answer to your question, but maybe can serve as a helper point. I'm looking for the answer myself. Hope your question gets the attention it deserves.

Last shot at undestanding what context is in Android

This will be my last try to understand what context means in Android, otherwise I will leave Android development because I don't understand why nobody can give a good answer to this. I do NOT WANT a copy paste from the Android docs that tell me that it is a interface for accessing resources. Either will I accept links to other questions because I have read them all, otherwise I wouldn't have asked.
As the documentation states it is a interface to the resources.
1st question
What is context? What does it mean that it is a interface to the resources?
2nd question
Why do we then pass this around all the time, would not every activity etc. have access to the same resources?
3rd question
Why is context needed in every friggin scenario? Such as Button myButton = new Button(this);
4th question
Yet another question about why context is passed to e.g. listadapters?
Thank you for your time:)
Would it help you to visualise a Context as a pointer to your parent object?
So, this is why in your example you create a Button with
Button myButton = new Button ( this );
The button (and Android) needs to know with which Activity it is to be associated in order to properly manage resources (as you yourself has said - don't forget, it's for Android just as much as for you or your user) and to know for example, when to trigger your onClick(). Without knowing in which Context your button exists, how does Android know whether to show it or not? How does Android know whether to send onClick() events or not? It's because it knows the context of the button.
If your buttons context is the same as the active Activity, then it's visible to the user and needs to be managed differently to an object that is not visible - for instance, the visible Activity and it's resources will be the last objects to be killed in an out-of-memory situation.
This is no different really to other operating systems and graphical toolkits, it's just different terminology.
A Context is an interface to resources, but the touchscreen is a resource, memory is a resource, the CPU is a resource - you are thinking too narrowly about what constitutes a resource (and again, it's really just semantics); resources aren't just sound files, or icons, or layouts - there are resources that Android manages too, and it needs to know the Context of your objects in order to manage those external resources properly.
Context is a means to register your objects with the system so that whenever system wants to respond to your object, it could be identified uniquely.
If you do not register your button with the system then the listener will not get the correct event and hence it will create mess and make your system crash/slow.
The concept of context is deep rooted in android. In simple terms here is my explanation:
Android is a multi-threaded platform.
There in one UI thread where everything the user sees is drawn and in the background there can be 'n' worker threads.
Every activity/service runs on its own thread.
Every activity has a local set of layouts/images/mp3's etc.
Every activity is identified in runtime by its 'Context'. Think of it as an identifier. Thus anything you might want to do within that activity you should do it with a reference of the context.
Hope this is a favorable answer for questions 1,2,3,4
1st question What is context? What
does it mean that it is a interface to
the resources?
Hmm.. Context I believe you understand that it tells you where exactly you are. As you know the concept of this pointer in Java it is same as that. The system provides each application a context. The resources needs to be mentioned that it has to be used in this context. And all these because Android is multi-threaded. It is not that you enter inside an activity and you will be dealing with just one thread.
2nd question Why do we then pass this
around all the time, would not every
activity etc. have access to the same
resources?
Well when we have one class and an inner class then if you use "this" inside the inner class then your components will take the inner class context and not the outer class context even if you meant the outer class. Here you will have to specify by saying your outer class name.this i.e you are specifying clearly that you want to use the outer class context.
Why is context needed in every friggin
scenario? Such as Button myButton = new
Button(this);
Now Button and any other widget needs to be known on which view they need to be. So by telling the context you make it clear to the widget. Say I have two classes inside a java file and now you use a button widget. How will the widget know exactly where it has to go.
I hope the answer for your forth question is also the same.

Categories

Resources