I was reading over the android documentation for toasts, and noticed that the example code uses getApplicationContext() rather than getActivity() or this. From the docs:
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Based on other sources, I have been given to understand that using getApplicationContext() is generally bad practice. Are toasts somehow an exception? If so, why? Or are the Android docs just wrong in this case?
I have been given to understand that using getApplicationContext() is generally bad practice
I would describe it more as "use Application when you know why you are using Application". Too many Android developers have negligible Java experience, get confused by inner classes, and think that they need to call getApplicationContext() (or getBaseContext()) to get a Context to pass as a parameter to something or another.
Dave Smith's epic blog post on the role of different Context implementations covers a fair number of the common use cases... though Toast is not among them.
Are toasts somehow an exception? If so, why?
Toasts work with Application as the Context, though there is no particular need to use an Application to show a Toast.
Or are the Android docs just wrong in this case?
They are not wrong, insofar as the code works. The JavaDocs for Toast in various places point out that Activity is also a fine Context to use, and I see nothing in the Toast source code to indicate otherwise.
It's important to note that Toast can be used even when your context is not visible or is not in control of any UI. In other words, the documentation is pointing out that you can have a minimal context (like that from a service) and still use Toast.
I don't believe that the documentation is trying to present a "best practice" for the use of Context, but rather to properly demonstrate this attribute of Toast.
I had a problem with Toast localization string when used application context. It worked properly with activity.
Related
I need to use Toast.makeText(getApplicationContext()). The getApplicationContext() is what I am really after. I need a specific tutorial on passing Context around. Any sugestions? I see alot of developers answering questions with techo-speak like this and I would seriously like to advance to that stage. I have run into passing Context issues way too often and would like a deep understanding of this. Until I get this type of knowledge I will always consider myself a noob.
Thanks.
Do you have a problem with Activity being a Context ? (Activity.this)??
Android already does that for you so why do you want to bother your head.? When you create a View the Context is passed to the View eg; TextView textv = new TextView(Context); you can later retrieve that Context with View.getContext(). Honestly Context are everywhere so why do you really want to use the getApplicationContext(); why not getBaseContext()
I have a class where I am getting context objects from more than 10 activities.
I want to know the context object of which activity is at the instant.
I have tried the following but no results.
context.equals(One.this);
context.equeals(One.class);
If any one having any idea please share with me!
I hope you aren't holding on to these Context references longer than necessary, I found out what a wonderful source of memory leaks this can be if not handled correctly!
If they are all Activity instances you can treat them as such and use:
if ( activity instanceof MyClassActivityOne ) {
// do something
}
Ten activities seems like a lot to have at once.
What are you trying to do by comparing context objects? Sometimes the answer to the question
"How do I do this?" is "Don't do this! Tell us what you want, and we'll suggest another
path to follow."
According to this answer or the android's documentation there is several ways to get the Context in an app and pass it to an other class/method/whateveruneed.
Let's say I'm in the Foo Activity and in need to pass the context to Bar's constructor.
Bar bar = new Bar(Foo.this);
Bar bar2 = new Bar(this); //same as first i guess
Bar bar3 = new Bar(getApplicationContext());
Bar bar4 = new Bar(getBaseContext());
Bar bar5 = new Bar(MyApp.getContext); // get context statically
Taking into account of memory leaks, speed , general performance , what will be the better way between all those possibilities ?
You should check out this question - which basicly covers the same as yours.
Also the Developer Docs on Avoiding memory leaks gives you a decent explanation of some situtations in which various of the methods are reasonable to use.
I think that this post will provide you enough information. Look at the first response.
Difference between Activity Context and Application Context
You would probably want to use this. It is the Context of your current Activity (Which is a context) and has shortest lifecycle. But be aware of the memory leak that could occur.
http://developer.android.com/resources/articles/avoiding-memory-leaks.html
I have not any direct answer to your question.But if you compare Foo.this and this then better to use first one as sometimes (in nested class case) second one will show error.
For more discussion on it go through that link
Using Application context everywhere?.
Hope it will help you
Android memory management. It covers all the aspects of Android memory management.
For context explanation this is a good answer.
Another good explanations of context.
Quick question: Is there a way to display a toast message that doesn't fade away until I call cancel() on it?
I have tried setting the duration to something like 9999 but that doesn't work.
Is there a way to display a toast message that doesn't fade away until I call cancel() on it?
No, not directly from the SDK, but you can "tweak" your Toast to make it live longer by calling show() on it as many times you wish using threads. See this article for more information.
A Toast that doesn't go away until you cancel it is called a Dialog (or AlertDialog). The integer you pass to Toast.setDuration() is a flag - not a value - it will only recognize the values Toast.LENGTH_SHORT and Toast.LENGTH_LONG.
The Toast calss description says:
"A toast is a view containing a quick little message for the user. The
toast class helps you create and show those..."
"...The idea is to be as unobtrusive as possible, while still showing the
user the information you want them to see. Two examples are the volume
control, and the brief message saying that your settings have been
saved..."
As for the duration parameter it should be one of LENGTH_LONG or LENGTH_SHORT - 1 or 0 respectively.
Use a dialogue that looks like a Toast if you really have to, but I don't recommend doing this because this wont be what a user expects from a Toast.
Toast Message works with time.there is no way to control it with the cancel.You have to use Dialog for the kind of purpose
The official doc says (http://developer.android.com/reference/android/widget/Toast.html#makeText(android.content.Context, int, int) ):
public static Toast makeText (Context context, int resId, int duration)
Since: API Level 1
Make a standard toast that just contains a text view with the text from a resource.
Parameters
context The context to use. Usually your Application or Activity object.
resId The resource id of the string resource to use. Can be formatted text.
duration How long to display the message. Either LENGTH_SHORT or LENGTH_LONG
Throws Resources.NotFoundException if the resource can't be found.
This means there is no direct way to do that. You will have to build your custom code for this. As Toasts exacly overlap each other you can call the same Toast every second with a thread as an example, and use a cancel() custom method to terminate that thread.
I know this post is old but for others that come across it you are more than welcome to use a little library I put together called SuperToasts.
You can find the library here.
There is an indeterminate option for Toasts that are added to an Activity namely the SuperActivityToast. I purposely did not add this feature to standard SuperToasts, a class that mimics standard Toasts, because the SuperToast can linger until your application is killed as it is added to the WindowManager and not an Activity. SuperActivityToasts are added to the Activity's content and will be destroyed along with your Activity hence the ability to make them indeterminate.
I need to get the context to be able to get a resource. Like this:
getApplicationContext().getResources().openRawResource( R.raw.texture );
I've seen the getApplicationContext() in the android documentation but when I try to use it in the above code it doesn't work - it doesn't exist.
I can send the context through functions to get it to where it's needed and it works. However, I find it cumbersome to send a variable through many functions that doesn't need or use it. Then I would rather just try to get it in the function that do. But the getApplicationContext(), as in the android documentation, doesn't work - http://developer.android.com/reference/android/content/Context.html
So how do I get the context so I can read resources? Or are my only option to send it through all my functions?
getApplicationContext() is a method of a Context. You have to have a context to get the resources. That's just how it works.
Just makes sure you're not storing a reference to your context anywhere or you could cause a memory leak.
In your activity you can use getResources() method immediately. For example
getResources().getDrawable(R.drawable.logo);
If you want to get some resource in some other class not in activity, you should pass context link in other class from your activity. For example
Util.convertLogo(this)
or
Util.convertLogo(getApplicationContext())