Sven van den Boogaart
Sven van den Boogaart

Reputation: 12325

Android show toast before methdod

Because you must include a legal notice when using google maps on android I added the following code to my fragment:

 //in oncreate view method
_noticeMaps.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            Toast.makeText(getActivity().getApplicationContext(), "Loading", Toast.LENGTH_LONG).show();
            showLegalNotice();
        }
 });


 public void showLegalNotice(){
    _legalNotice = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getActivity());
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Legal Notice");
    builder.setMessage(_legalNotice);
    AlertDialog dialog = builder.create();
    dialog.show();
}

Because the legal notice takes a long time to be placed in the setMessage the app shows the dialog after a few seconds (5+). Thats why i added the toast before the showLegalNotice to notice the user that its loading. However the toast shows after the dialog is loaded. Why isnt the toast showing before the dialog is loading? I call showLegalNotice AFTER i create the toast. I know i can fix it with threads but I want to understand why the toast is showing after the dialog is created.

Upvotes: 0

Views: 220

Answers (1)

Aritra Roy
Aritra Roy

Reputation: 15625

The best solution is to put the legalNotice method codes in an AsyncTask. The Toast is shown after the dialog because you are doing the heavy work on the UI thread which is making it busy and that's why the toast is lagging behind.

If you don't know about AsyncTask, you can learn about it here. You can show the Toast in the preExecute() method of the AsyncTask. It will be guaranteed that the toast will be shown before any other action is taken.

UPDATE

Yes, you are right. The code is run in a sequential manner so the Toast should have been shown before the method runs. But try to think in a different way.

The Toast is an system UI component. You call show() on toast and your code moves to the next heavy or long-running task almost instantly.

There is always a slight delay for the toasts to be drawn or initiated on your screen and it also depends on various flavours of Android. So, before the toast starts to draw on the screen, the UI thread gets busy or jammed on performing a long-running task and looses frames.

Just when the long-running task of your method ends, the UI thread gets free once again and is able to resume drawing the toast. That is why, the toast is displayed, but always after the method completed its execution.

Upvotes: 3

Related Questions