How to use toast message inside Thread in Android

后端 未结 7 1138
故里飘歌
故里飘歌 2020-12-20 00:19

I am facing some problems when I\'m using Toast inside run method of Thread class.

My error Logcat

09-16 11:42:38.140: E/AndroidRuntime(1446): in wri         


        
相关标签:
7条回答
  • 2020-12-20 00:24

    You need to call toast inside onPostExecute() method

    @Override
    protected void onPostExecute(Boolean result)
    {
        super.onPostExecute(result);
        Toast.makeText(context, "Message", Toast.LENGTH_SHORT).show();
    }
    
    0 讨论(0)
  • 2020-12-20 00:28

    You've to call the Toast on UI thread.

    AsyncTask onPostExecute runs on UI thread. If you want to "force" a UI thread, you can use the following code inside onBackground:

    // code runs in a thread
       runOnUiThread(new Runnable() {
          @Override
              public void run() {
                  Toast.makeText(....).show();
              }
       });
    
    0 讨论(0)
  • 2020-12-20 00:29

    According to your logcat you are trying to update UI part (using Toast) in doInBackground() of AsyncTask which is not possible directly

    Use same in onPostExecute() which is used for handling/updating UI Part

    If you want to show Toast in doInbackground() wrap the Toast in runOnUIThread() but this isn't the best solution.

    like

    runOnUiThread(new Runnable() {
          @Override
              public void run() {
                  // Show Toast Here
              }
       });
    
    0 讨论(0)
  • 2020-12-20 00:34

    You may display your Toast message as below:

    YourActivityName.this.runOnUiThread(new Runnable() {
    
            @Override
            public void run() {
                Toast.makeText(YourActivityName.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();
    
            }
        });
    
    0 讨论(0)
  • 2020-12-20 00:46

    By calling an Activity's runOnUiThread method from your Thread:

    activity.runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(activity, "Toast message inside Thread", Toast.LENGTH_LONG).show();
        }
    });
    
    0 讨论(0)
  • 2020-12-20 00:47

    You can not use or access any UI elements inside a non UI thread. If you want to see some messages about your thread then you may use AsyncTask and use the UI stuffs inside preExecute method.because the pre and postExecute of AsyncTask are run on UI thread.

    If you want to do like so then see Problem with Toast in AsyncTask method call .

    If you are excepting a small and easy way, then just use LOG class like:

    Log.d("String Key", "the value you want to see");
    

    If you want some ideas about log then please see Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

    Hope these are sufficient for your question.

    0 讨论(0)
提交回复
热议问题