4

Can I use runOnUiThread at fragment. And how to do it in fragment?

 MainActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MainActivity.this,"any mesage",Toast.LENGTH_LONG).show();
        }
    });
Nabin
  • 11,216
  • 8
  • 63
  • 98
yousef
  • 1,345
  • 1
  • 12
  • 20
  • What is your requirement to run on ui thread , are you using any background task in your fragment because in a fragment you are in the ui thread – MaxExplode Aug 06 '15 at 03:06
  • 2
    http://stackoverflow.com/questions/16425146/runonuithread-in-fragment Please see here it may help you. –  Jan 12 '16 at 11:22

2 Answers2

8

try

getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getActivity(),"any mesage",Toast.LENGTH_LONG).show();
        }
    });
Deepak Goyal
  • 4,747
  • 2
  • 21
  • 46
4

Use getActivity() instead of MainActivity.this. Also use getApplicationContext() for the Toast.makeText() method

getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getActivity().getApplicationContext(),"any mesage",Toast.LENGTH_LONG).show();
        }
    });
Nabin
  • 11,216
  • 8
  • 63
  • 98