26

I searched many places but could not find a complete working example of implementation of "runOnUiThread". I tried a lot , but getting lots of errors . I just want to display a toast from a thread.

Sourav301
  • 1,259
  • 1
  • 14
  • 24

3 Answers3

34

So here is the final full code. Thanks to all who have replied.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MainActivity.this.runOnUiThread(new Runnable() {

        public void run() {
            Toast.makeText(MainActivity.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();

        }
    });
}

}

And About the XML, its is the default XML file created. No change needed.

Sourav301
  • 1,259
  • 1
  • 14
  • 24
12
YourActivityName.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(YourActivityName.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();

            }
        });
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
  • 1
    Is it possible to do this from another class? right now my MainActivity starts a thread in another class and I would like that class/thread to use a toast message. – Nefariis Apr 16 '14 at 19:27
0

To answer Nefariis question, I had the same problem, and needed to toast from a non-activity class, to solve it you can pass Context to the function your calling runOnUiThread from.

For example:

public class FlashCardsUtil
{
    public static void fillTableFromFile(SQLiteDatabase pSqLiteDatabase, final Context pContext, String pFileName)
    {
        ...

        runOnUiThread(new Runnable()
        {
            public void run()
            {
                Toast.makeText(pContext, "Success filling database", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
deepGrave
  • 320
  • 3
  • 11