Search code examples
androidtry-catchtoast

Show toast within try-catch block


I am new to android programming and trying to develop a simple app where I am trying to send email by using a try catch block as shown below:

new Thread(new Runnable() {
public void run() {
    try {       
        GMailSender sender = new GMailSender("username@gmail.com","password");
            sender.sendMail("Test mail","This mail has been sent from android app along with attachment","username@gmail.com","Someuser1@gmail.com");
            } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "Error",Toast.LENGTH_LONG).show();
        }
    }
}).start();

From the above code when the email sending is failed I get an error displayed using toast. But Now I would like to know If the mail is sent successfully I need to display the toast

This is what I have tried but the app is getting crashed and unable to display any toast

new Thread(new Runnable() {
public void run() {
    try {       
            GMailSender sender = new GMailSender("username@gmail.com","password");
                sender.sendMail("Test mail","This mail has been sent from android app along with attachment","username@gmail.com","Someuser1@gmail.com");
            Toast.makeText(getApplicationContext(), "Success",Toast.LENGTH_LONG).show();
                } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Error",Toast.LENGTH_LONG).show();
            }
        }
    }).start();

can anyone guide to the right way of doing this to achieve my goal.


Solution

  • Use the below code to show toast put the ui related contents within UI thread

    runOnUiThread(new Runnable(){
    public void run() {
       Toast.makeText(getApplicationContext(), "Error",Toast.LENGTH_LONG).show();
    }
    });