Android: Adding a delay to the display of toast?

≯℡__Kan透↙ 提交于 2019-11-29 17:44:48

Try this..

Use Handler

            // Handler which will run after 2 seconds.
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                      Toast.makeText(MathsGameResults.this,
                                "Data is successfully uploaded.",
                                Toast.LENGTH_LONG).show();
                }
            }, 2000);

Delaying the code might not always work successfully especially on devices with a low RAM. Here is what you can do.

Define this variable

boolean result;

Add this code at end of loginDataBaseAdapter code if the data is successfully uploaded

result = true;
showResult(result);

Then add this method -

public void showResult(boolean i){

    if (result == true;) {

        loginDataBaseAdapter.updateUploadedRecord(sessionId);

        Toast.makeText(
                          MathsGameResults.this,
                          "Data is successfully uploaded.",
                          Toast.LENGTH_LONG
                      ).show();

    } else {

        Toast.makeText(
                       MathsGameResults.this,
                       "Error while uploading. Please try again later.",
                       Toast.LENGTH_LONG
                      ).show();
    }         
}

Anyways here is how to delay the code -

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            if (result == true;) {

                loginDataBaseAdapter.updateUploadedRecord(sessionId);

                Toast.makeText(
                                MathsGameResults.this,
                                "Data is successfully uploaded.",
                                Toast.LENGTH_LONG
                              ).show();

            } else {

                Toast.makeText(
                               MathsGameResults.this,
                               "Error while uploading. Please try again later.",
                               Toast.LENGTH_LONG
                              ).show();
           }

        }
}, 5000);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!