Android: Adding a delay to the display of toast?

前端 未结 2 1515
隐瞒了意图╮
隐瞒了意图╮ 2020-12-22 04:44

I wish to display a toast if a certain condition is true or false. However I want this toast to delay for two secon

相关标签:
2条回答
  • 2020-12-22 05:26

    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);
    
    0 讨论(0)
  • 2020-12-22 05:31

    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);
    
    0 讨论(0)
提交回复
热议问题