Which context to use for Toast in Android? - android

I just learned that I can use either:
Toast.makeText(MainActivity.this, R.string.some_string,Toast.LENGTH_SHORT).show();
or,
Toast.makeText(getApplicationContext(), R.string.some_string,Toast.LENGTH_SHORT).show();
To display a Toast in Android.
Earlier I thought context was actually a sort of handle to the parent window where it should be display but the documentation is unclear about this.
Then I came across this table:
It also doesn't seem to mention what context exactly to use for a Toast?
Edit:
Is context like a "handle to parent window" for the sub-window like Toast? or does it actually allow the Toast.makeText to get access to resources or something?
Why is it being used at all if the context doesn't matter?

Looking at Toast.java, I can see the Context is used only for:
obtaining Resources
obtaining Package Name
getText which is actually same as #1
So apparently there's no difference whether it's Activity or ApplicationContext, unless those resources depend on theme (which is not the case as far as I can tell).
And no, the context passed to Toast is not a handle to parent window in any sense.

I'd recommend to use the activity in your case. Since you're calling from the activity itself. The activity is a Context and you're using the method on the activity to get another context (the application). It is a little unnecessary.
However in the case you're calling a toast from somewhere else it might be a better idea to use the application, since the application will always be there while your app is active.

You can show Toast only from UI (main thread) context. If you want show this from Service (but this is contradicts Google guidelines), you can do this way: Show toast at current Activity from service

For toasts, which are short-lived, you can usually use whatever context you want. Typically, you would use the activity context, but application context is fine as well.

Related

Toast: Docs' tutorials say to use getApplicationContext, but Docs References say to use getApplication or getActivity

https://developer.android.com/guide/topics/ui/notifiers/toasts: in the sources examples, they use getApplicationContext.
https://developer.android.com/reference/android/widget/Toast.html#makeText(android.content.Context,%20int,%20int): "Context: The context to use. Usually your Application or Activity object.".
What should we use in definitive?
To answer this question, I think one should think about...:
The lifecycle of the object Toast defined in a fragment, and then the lifecycle of Toast defined in an activity
The risk of memory leaks if we use getActivity, which depends on the Toast
https://blog.mindorks.com/understanding-context-in-android-application-330913e32514: here, it seems that one should use getActivity for Toast.
What should we use in definitive?
Generally speaking: if the Context is being applied to something for the UI, use the Activity, so that your current theme can be taken into account. Toast is UI; therefore, use the Activity.
In reality, I don't think that a Toast necessarily uses anything from the theme.
The lifecycle of the object Toast defined in a fragment, and then the lifecycle of Toast defined in an activity
Those are the same thing, since a fragment is unrelated to a Toast. You do not pass a Fragment to any method on Toast.
The risk of memory leaks if we use getActivity, which depends on the Toast
Since the Toast is short-lived, any possible leak is short-lived. Leaks are a problem when the leaked material is referenced for an indefinite period of time and so will not get cleaned up.

Android - what effect do different contexts have in code performance? [duplicate]

There has been a lot of posting about what these two contexts are.. But I'm still not getting it quite right
As I understand it so far:
Each is an instance of its class which means that some programmers recommend you to use this.getApplicationContext() as often as possible in order to not "leak" out any memory. This is because the other this (getting the Activity instance context) points to an Activity that is being destroyed each time the user tilts the phone or leave the app etc.. Which apparently the Garbage Collector (GC) doesn't catch and therefore uses too much memory..
But can anyone please come up with some really good coding examples where it would be the right thing to use this (getting the context of the current Activity instance) and the application context will be useless/wrong?
getApplicationContext() is almost always wrong. Ms. Hackborn (among others) have been very explicit that you only use getApplicationContext() when you know why you are using getApplicationContext() and only when you need to use getApplicationContext().
To be blunt, "some programmers" use getApplicationContext() (or getBaseContext(), to a lesser extent) because their Java experience is limited. They implement an inner class (e.g., an OnClickListener for a Button in an Activity) and need a Context. Rather than using MyActivity.this to get at the outer class' this, they use getApplicationContext() or getBaseContext() to get a Context object.
You only use getApplicationContext() when you know you need a Context for something that may live longer than any other likely Context you have at your disposal. Scenarios include:
Use getApplicationContext() if you need something tied to a Context that itself will have global scope. I use getApplicationContext(), for example, in WakefulIntentService, for the static WakeLock to be used for the service. Since that WakeLock is static, and I need a Context to get at PowerManager to create it, it is safest to use getApplicationContext().
Use getApplicationContext() when you bind to a Service from an Activity, if you wish to pass the ServiceConnection (i.e., the handle to the binding) between Activity instances via onRetainNonConfigurationInstance(). Android internally tracks bindings via these ServiceConnections and holds references to the Contexts that create the bindings. If you bind from the Activity, then the new Activity instance will have a reference to the ServiceConnection which has an implicit reference to the old Activity, and the old Activity cannot be garbage collected.
Some developers use custom subclasses of Application for their own global data, which they retrieve via getApplicationContext(). That's certainly possible. I prefer static data members, if for no other reason than you can only have one custom Application object. I built one app using a custom Application object and found it to be painful. Ms. Hackborn also agrees with this position.
Here are reasons why not to use getApplicationContext() wherever you go:
It's not a complete Context, supporting everything that Activity does. Various things you will try to do with this Context will fail, mostly related to the GUI.
It can create memory leaks, if the Context from getApplicationContext() holds onto something created by your calls on it that you don't clean up. With an Activity, if it holds onto something, once the Activity gets garbage collected, everything else flushes out too. The Application object remains for the lifetime of your process.
I think there's a lot of stuff that is poorly documented on the SDK site, this is one of them. The claim I'm going to make is that it seems as though it's better to default to using an application context and only use an activity context when you really need to. The only place where I've ever seen that you need an activity context is for a progress dialog. SBERG412 claims that you have to use an activity context for a toast message, yet the Android docs clearly show an application context being used. I've always used application context for toasts because of this Google example. If it's wrong to do so, then Google dropped the ball here.
Here's more to think about and review:
For a toast message, the Google Dev Guide uses the application context and explicitly say's to use it:
Toast Notifications
In the dialogs section of the Dev guide, you see that an AlertDialog.Builder uses the application context, and then the progress bar uses an activity context. This isn't explained by Google.
Dialogs
It seems like a good reason to use application context is when you want to handle configuration changes like an orientation change, and you want to retain objects which need a context like Views. If you look here: Run Time Changes
There is a caution about using an activity context, which can create a leak. This can be avoided with an application context with the views that are to be retained (at least that's my understanding). In an app I'm writing, I intend to use an application context because I'm trying to hold over some views and other things on an orientation change, and I still want the activity to be destroy and recreated on orientation changes. Thus I have to use an app context to not cause a memory leak (see Avoiding memory Leaks). To me it seems there are plenty of good reasons to use the application context instead of an activity context, and to me it almost seems like you would use it more often than an activity context. That's what many Android books I've gone through seem to do, and that's what much of the Google examples I've seen do.
The Google documentation really makes it seem like using application context is perfectly fine in most cases, and in fact appears more often than using an activity context in their examples (at least the examples I've seen). If it's really such a problem to use application context, then Google really needs to place more emphasis on this. They need to make it clear, and they need to redo some of their examples. I wouldn't blame this entirely on inexperienced developers since the authority (Google) really makes it look like it's not a problem to use application contexts.
I used this table as a guidance for when to use the different types of Context such as Application context (i.e: getApplicationContext()) and activity context , also BroadcastReceiver context:
All merits go to original author here for more info.
Which context to use?
There are two types of Context:
Application context is associated with the application and will always be same throughout the life of application -- it does not change. So if you are using Toast, you can use application context or even activity context (both) because toast can be displayed from anywhere with in your application and is not attached to a specific window. But there are many exceptions, one exception is when you need to use or pass the activity context.
Activity context is associated with to the activity and can be destroyed if the activity is destroyed -- there may be multiple activities (more than likely) with a single application. And sometimes you absolutely need the activity context handle. For example, should you launch a new activity, you need to use activity context in its Intent so that the new launching activity is connected to the current activity in terms of activity stack. However, you may use application's context too to launch a new activity but then you need to set flag Intent.FLAG_ACTIVITY_NEW_TASK in intent to treat it as a new task.
Let's consider some cases:
MainActivity.this refers to the MainActivity context which extends Activity class but the base class (activity) also extends Context class, so it can be used to offer activity context.
getBaseContext() offers activity context.
getApplication() offers application context.
getApplicationContext() also offers application context.
For more information please check this link.
I was wondering why not to use Application Context for every operation which it supports. In the end it lowers chance of memory leak and missing null check for getContext() or getActivity() (when using injected application context or acquired through static method from Application). Statements, like the one by Ms. Hackborn to use Application Context only if needed, don't seem convincing for me without an explanation why. But it seems that I have found an unswear why:
have found that there are issues on some Android version / device combinations that do not follow these rules. For instance, if I have a BroadcastReceiver that is passed a Context and I convert that Context to an Application Context and then try to call registerReceiver() on the Application Context there are many instances where this works fine, but also many instances where I get a crash because of a ReceiverCallNotAllowedException. These crashes occur on a wide range of Android versions from API 15 up to 22.
https://possiblemobile.com/2013/06/context/#comment-2443283153
Because it's not guaranteed that all operations described as supported by Application Context in the table below will work on all Android devices!
Two great examples of when you should use Activity context vs. the Application context are when displaying either a Toast message or a built-in Dialog message as using the Application context will cause an exception:
ProgressDialog.show(this, ....);
or
Toast t = Toast.makeText(this,....);
Both of these need information from the Activity context that is not provided in the Application context.
Application context live untill your application is alive only and it is not depend on Activity Life Cycle but, context keep object long-lived. If the object which you are used temporary, that time use Application Context and Activity Context is used totally oposite of Application Context.

does it guarantee to give same result in getDefaultSharedPreferences within Context?

I read this discussion but still have a question.
If I use getDefaultSharedPreferences(getApplicationContext()) and getDefaultSharedPreferences(SomeActivity.this), does it gurantee to give same result (same xml preference file access)?
yes it does. The context parameter is used to get the package name, that will be used as name for the xml file in which android stores your values. You can see the androis's source code here
Wishing you a happy new year-2014
Both will behave same !!
View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.
Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.
ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().
Please Note that behind the scenes
getDefaultSharedPreferences(context)
calls
getSharedPreferences(context.getPackageName(), MODE_PRIVATE)
as far as I understand: Context is the Base Object. So every Activity same as Application derives from Context. This means that every Activity and every Application IS a Context;
Hope now you understand the things so we can say that they will produce same behave.
Please refer http://developer.android.com/reference/android/app/Activity.html
and
http://developer.android.com/reference/android/content/Context.html

When to call activity context OR application context?

There has been a lot of posting about what these two contexts are.. But I'm still not getting it quite right
As I understand it so far:
Each is an instance of its class which means that some programmers recommend you to use this.getApplicationContext() as often as possible in order to not "leak" out any memory. This is because the other this (getting the Activity instance context) points to an Activity that is being destroyed each time the user tilts the phone or leave the app etc.. Which apparently the Garbage Collector (GC) doesn't catch and therefore uses too much memory..
But can anyone please come up with some really good coding examples where it would be the right thing to use this (getting the context of the current Activity instance) and the application context will be useless/wrong?
getApplicationContext() is almost always wrong. Ms. Hackborn (among others) have been very explicit that you only use getApplicationContext() when you know why you are using getApplicationContext() and only when you need to use getApplicationContext().
To be blunt, "some programmers" use getApplicationContext() (or getBaseContext(), to a lesser extent) because their Java experience is limited. They implement an inner class (e.g., an OnClickListener for a Button in an Activity) and need a Context. Rather than using MyActivity.this to get at the outer class' this, they use getApplicationContext() or getBaseContext() to get a Context object.
You only use getApplicationContext() when you know you need a Context for something that may live longer than any other likely Context you have at your disposal. Scenarios include:
Use getApplicationContext() if you need something tied to a Context that itself will have global scope. I use getApplicationContext(), for example, in WakefulIntentService, for the static WakeLock to be used for the service. Since that WakeLock is static, and I need a Context to get at PowerManager to create it, it is safest to use getApplicationContext().
Use getApplicationContext() when you bind to a Service from an Activity, if you wish to pass the ServiceConnection (i.e., the handle to the binding) between Activity instances via onRetainNonConfigurationInstance(). Android internally tracks bindings via these ServiceConnections and holds references to the Contexts that create the bindings. If you bind from the Activity, then the new Activity instance will have a reference to the ServiceConnection which has an implicit reference to the old Activity, and the old Activity cannot be garbage collected.
Some developers use custom subclasses of Application for their own global data, which they retrieve via getApplicationContext(). That's certainly possible. I prefer static data members, if for no other reason than you can only have one custom Application object. I built one app using a custom Application object and found it to be painful. Ms. Hackborn also agrees with this position.
Here are reasons why not to use getApplicationContext() wherever you go:
It's not a complete Context, supporting everything that Activity does. Various things you will try to do with this Context will fail, mostly related to the GUI.
It can create memory leaks, if the Context from getApplicationContext() holds onto something created by your calls on it that you don't clean up. With an Activity, if it holds onto something, once the Activity gets garbage collected, everything else flushes out too. The Application object remains for the lifetime of your process.
I think there's a lot of stuff that is poorly documented on the SDK site, this is one of them. The claim I'm going to make is that it seems as though it's better to default to using an application context and only use an activity context when you really need to. The only place where I've ever seen that you need an activity context is for a progress dialog. SBERG412 claims that you have to use an activity context for a toast message, yet the Android docs clearly show an application context being used. I've always used application context for toasts because of this Google example. If it's wrong to do so, then Google dropped the ball here.
Here's more to think about and review:
For a toast message, the Google Dev Guide uses the application context and explicitly say's to use it:
Toast Notifications
In the dialogs section of the Dev guide, you see that an AlertDialog.Builder uses the application context, and then the progress bar uses an activity context. This isn't explained by Google.
Dialogs
It seems like a good reason to use application context is when you want to handle configuration changes like an orientation change, and you want to retain objects which need a context like Views. If you look here: Run Time Changes
There is a caution about using an activity context, which can create a leak. This can be avoided with an application context with the views that are to be retained (at least that's my understanding). In an app I'm writing, I intend to use an application context because I'm trying to hold over some views and other things on an orientation change, and I still want the activity to be destroy and recreated on orientation changes. Thus I have to use an app context to not cause a memory leak (see Avoiding memory Leaks). To me it seems there are plenty of good reasons to use the application context instead of an activity context, and to me it almost seems like you would use it more often than an activity context. That's what many Android books I've gone through seem to do, and that's what much of the Google examples I've seen do.
The Google documentation really makes it seem like using application context is perfectly fine in most cases, and in fact appears more often than using an activity context in their examples (at least the examples I've seen). If it's really such a problem to use application context, then Google really needs to place more emphasis on this. They need to make it clear, and they need to redo some of their examples. I wouldn't blame this entirely on inexperienced developers since the authority (Google) really makes it look like it's not a problem to use application contexts.
I used this table as a guidance for when to use the different types of Context such as Application context (i.e: getApplicationContext()) and activity context , also BroadcastReceiver context:
All merits go to original author here for more info.
Which context to use?
There are two types of Context:
Application context is associated with the application and will always be same throughout the life of application -- it does not change. So if you are using Toast, you can use application context or even activity context (both) because toast can be displayed from anywhere with in your application and is not attached to a specific window. But there are many exceptions, one exception is when you need to use or pass the activity context.
Activity context is associated with to the activity and can be destroyed if the activity is destroyed -- there may be multiple activities (more than likely) with a single application. And sometimes you absolutely need the activity context handle. For example, should you launch a new activity, you need to use activity context in its Intent so that the new launching activity is connected to the current activity in terms of activity stack. However, you may use application's context too to launch a new activity but then you need to set flag Intent.FLAG_ACTIVITY_NEW_TASK in intent to treat it as a new task.
Let's consider some cases:
MainActivity.this refers to the MainActivity context which extends Activity class but the base class (activity) also extends Context class, so it can be used to offer activity context.
getBaseContext() offers activity context.
getApplication() offers application context.
getApplicationContext() also offers application context.
For more information please check this link.
I was wondering why not to use Application Context for every operation which it supports. In the end it lowers chance of memory leak and missing null check for getContext() or getActivity() (when using injected application context or acquired through static method from Application). Statements, like the one by Ms. Hackborn to use Application Context only if needed, don't seem convincing for me without an explanation why. But it seems that I have found an unswear why:
have found that there are issues on some Android version / device combinations that do not follow these rules. For instance, if I have a BroadcastReceiver that is passed a Context and I convert that Context to an Application Context and then try to call registerReceiver() on the Application Context there are many instances where this works fine, but also many instances where I get a crash because of a ReceiverCallNotAllowedException. These crashes occur on a wide range of Android versions from API 15 up to 22.
https://possiblemobile.com/2013/06/context/#comment-2443283153
Because it's not guaranteed that all operations described as supported by Application Context in the table below will work on all Android devices!
Two great examples of when you should use Activity context vs. the Application context are when displaying either a Toast message or a built-in Dialog message as using the Application context will cause an exception:
ProgressDialog.show(this, ....);
or
Toast t = Toast.makeText(this,....);
Both of these need information from the Activity context that is not provided in the Application context.
Application context live untill your application is alive only and it is not depend on Activity Life Cycle but, context keep object long-lived. If the object which you are used temporary, that time use Application Context and Activity Context is used totally oposite of Application Context.

How to display toast from one activity to another

I have a question. Is it possible to display a toast message (in if condition) from HttpDownload class to AnimalBadger class? (Both classes extend Activity)
if (((Node) textNodes.item(i)).getNodeValue().equals("a waning quarter moon"))
{
Toast.makeText(HttpDownload.this, "Some text...", Toast.LENGTH_LONG).show();
}
Thanks for the answers...
The first argument is just to get the Context to create the Toast with. You can use either activity or even getApplicationContext(). For simplicity, you usually use the closest available Context, which in this case would be your containing activity.
Toasts are not sent between application components, they take the form of small notifications usually at the bottom of the screen, and are a way to communicate low-priority messages to the user.
You may want to read the Creating Toast Notifications article in the documentation.
You could use a call back function and register it with HttpDownload class. That way the call back is called which will throw the toast(pun intended).

Categories

Resources