Why does toast shows with delay

Viewed 51

When I run the code which looks like:

Toast.makeText(MainActivity.this,"Toast 1", Toast.LENGTH_SHORT).show();
Log.i("MyLog","Log 1");

try {
   Thread.sleep( 5000);
} catch (InterruptedException e) {
   e.printStackTrace();
}

Toast.makeText(MainActivity.this,"Toast 2", Toast.LENGTH_SHORT).show();
Log.i("MyLog","Log 2");

It shows Log1 then make 5 sec delay then show Log2, Toast1, Toast2. Could anybody help me to understand why Toast1 does not appear befor delay?

Whole class is:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn = findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Toast.makeText(MainActivity.this,"Toast 1", Toast.LENGTH_SHORT).show();
            Log.i("MyLog","Log 1");
            try {
                Thread.sleep( 5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Toast.makeText(MainActivity.this,"Toast 2", Toast.LENGTH_SHORT).show();
            Log.i("MyLog","Log 2");
        }
    });
}

}

1 Answers

Thread.sleep( 5000) blocks your UI thread. The whole UI doesn't do anything for 5 seconds. So even if the first Toast has been created, the process of showing the Toast can get interrupted. You should move the delay to a background thread and start the second toast from the background thread.

A low effort solution would be to use Handler:

Toast.makeText(requireContext(), "Toast 1", Toast.LENGTH_SHORT).show()
Log.i("MyLog", "Log 1")

Handler().run {
    try {
        Thread.sleep(5000)
    } catch (e: InterruptedException) {
        e.printStackTrace()
    }
    Toast.makeText(requireContext(), "Toast 2", Toast.LENGTH_SHORT).show()
    Log.i("MyLog", "Log 2")
}

Note: This example is written in Kotlin.

Related