I am getting an error as Null pointer exception and unable to instantiate activity when I am creating a toast in activity constructor.I want to know the reason why toasts are working in onCreate method but not in activity constructor
The OS is responsible for constructing your Activity classes. This is because it needs to perform some setup, including providing the Activity a proper base Context. Without this, you cannot make Toasts.
In general, you should avoid doing anything in the constructor of an Activity (and you should definitely not be making instances of them yourself using new).
Usually a Toast appears as a feedback to user input (say a button click) or when some external event is registerd (say a network error happend or new incoming data is available).
However, to me it sounds as though you want to show a Toast right after opening your activity, is that correct? Then you should put it in the onCreate method of your activity. An example Toast is made like this
Toast.makeText(MainActivity.this, "Hello World", Toast.LENGTH_LONG).show();
You might also consider putting this call in the onResume method. I recommend getting familiar with activity lifecycles.
Instead of using Toasts you might also want to check out Snackbars.
Related
Inside onCreate of Application class, I set its instance to a static field, then show all application Toasts through this context. All works good except one thing, in some places a Toast can be shown before first activity can even appear but Toast never appears or sometimes just flashes. I think its because Activity not shown or drawn yet ? Or I'm missing something.
Edit:
More like showing toast from onCreate of Application class
Edit 2 :
public class TestApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Test from App", Toast.LENGTH_LONG).show();
}
}
If you want to show a Toast without the application even started manually by the user you can register a BroadcastReceiver which listens to the BOOT_COMPLETED system broadcast and then start a Service which will handle your Toasts.
You'll find many examples on how to do this.
To make a Toast before drawing your layout resources, just do this following.
//put this code before your setContentView(R.layout.your_layout);
Toast.makeText(yourclassName.this,"your text here",5000).show();
Well, consider one thing. If you want this toast to be shown before loading your activity and notify users some message. Then it might not be possible always. Because, The time Toast is shown with fraction of nano/mili seconds your layout is being loaded as-well.Moreover, scenario is totally different when you are on a real device and on a emulator.This might be the cause you got a flash of your Toast message. Just run it on a real device and you will see the differences.
Hope that helps
My app may launch a sub-activity for a specific purpose. When that activity finishes, I get the results in onActivityResult. These results are then processed in the subsequent onResume. This consists of a setContentView and also starting an AsyncTask that puts up a ProgressDialog.
This all works well when initiated the normal way, which is via a user request (i.e., menu selection) after the app is up and running. However, under some conditions I need to do this right as the app is starting up, so I initiate this sequence right from my onCreate. What then happens is that I get fatal ResourceNotFound errors within any o/s call that implicitly calls the layout inflater. I got around this with setContentView by pre-inflating the view in my onCreate method, but the AsyncTask's onPreExecute still fails on ProgressDialog.show() as it "fails to find" Android's own progress_dialog.xml!
Anyone know what's happening here?
I suspect it's something to do with the timing, where this is occurring before the main activity has even had a chance to display its screen. These calls are all being made on the main UI thread, but maybe something hasn't completed within the o/s under these conditions.
As a closeout, the problem turned out to be totally unrelated to what I described in my post. Turns out it was due to blindly using some code that had been posted in some online forum showing how to get and use AssetManager. Trouble is, at the end of the block of code he had put "assMan.close()". Well, this closes the asset manager for the entire activity and resources can no longer be accessed!
It took a while to find it since it was not something that I did via my own understanding.
I have a class that fetches data in response to button presses in the main activity. Unfortunately, I keep running into problems because this class is not an Activity or a Service. For example, without a Context I cannot translate a resource id into a string:
getString(R.string.example_string); // Doesn't work
Should I make this class into a Service and have the main Activity stop the class when it is closed? Should I pass the Context from the Activity into this class like this?
MyClass c = new MyClass(this);
Or is there some better way to handle this problem?
This issue also comes up when I try to send a Toast from this class.
Update: Erich and Janusz pointed me in the direction of the AsyncTask class which works perfectly, except that it creates a new thread and never kills that thread. This means that ever time the user presses a button, another thread is added and the old ones just sit there.
If you have a background action whose lifecycle is decoupled from your activity, I would use a Service. In that case, the Service will have its own Context, so you won't need to pass it in. If, however, you need to perform a background action in response to a UI event (and optionally post the results back into the UI thread), I would recommend you use an AsyncTask.
I agree with Erich, if you only have a something small like posting a change to a web backend or loading something from the phone memory to show it on screen use a Async Task. If the task will exit very "quick" (some seconds) you can make an anonymous class inside your activity. This will enable you to use a implicit reference to the outer activity inside the task and you can get your context from there.
If the task is running for a longer time you can pass down the context. If you are passing down the context try to not pass this from the activity use this.getApplicationContext() this will minimize the number of references to your activity and enable the garbage collector to clean up properly.
I'm trying to display an AlertDialog inside of another AlertDialog. When the user clicks on the any item within the initial AlertDialog another AlertDialog is created and shown.
I'm following the correct pattern for creating and displaying AlertDialogs, the problem is as soon as the code reaches the point where the innerDialog.show() method is encountered the application fails. The logcat prints an uncaught runtime exception:
android.view.WindowManager$BadTokenException : Unable to add window -- token null is not for an applicaion
I'm wondering if i'm allowed to call the show() method on the innerAlertDialog manually.
The outer AlertDialog is working because i'm using the callback onCreateDialog() method.
In previous versions there was a bug where getApplicationContext() returned null.
I still dont quite if it has been fixed however with dialogs, its always better to send this.
And for the main question, its working as designed to avoid locking the UI thread.
I have seen people recommending creating a new layout with the theme of the dialog and start the activity on the first dialog, however I havent try this yet.
I know Android's Activity model is a bit different from what I usually consider to be an "app".
I want to do something (in this case, check some notifications on a server and show them if available) when my app is "launched". What is a good way to accomplish this?
I likely don't want to do it in an activity's OnCreate, since each activity can be created any number of times - the code would get called more often than necessary.
The app also has multiple entry points - would I have to duplicate the check in each activity?
What I'm thinking of doing is setting up this code inside the Application object, along with a flag that tracks whether it's already been called - and just call it from each Activity's onCreate().
Is there a better or more "proper" way to do this?
The right, Android-approved way to do this is:
Create your own android.app.Application class
Override the onCreate method
In the AndroidManifest.xml, change the android:name attribute of the application element to the name of your class
Now, whenever your app is "started" (any one of your activites is started for the first time and no other instances are alive) onCreate will be called.
You may also find the onTerminate method useful.
Can you just check if the bundle passed to onCreate() is null?
It's not null "If the activity is being re-initialized after previously being shut down..."
There's probably no harm in putting it in onCreate; the Activity is really only destroyed when the OS needs the RAM for something else, not when the user goes to another app.
EDIT: You can also have a Service that runs when the device gets booted up, too. This might be a better option if you also want to check when the app starts, since you'll only have to call context.startService from the Activity to run the check. Just be sure to stop it when it's done if you don't need it to be persistent.