0

I got this error in android api 14 (4.0) and lower but in api level 15 and upper every thing work fine.Why?

thread = new Thread(new Runnable() {
                public void run() {
                    try {
                        //do some thing
                    } catch (Exception e) {

                    } finally {

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //do some thing
                            }

                        });
                    }

                }
            });

            thread.start();
m n
  • 223
  • 1
  • 7
  • 19

1 Answers1

0

you can not display toast message from thread. you need actvity UI thread to display any Ui elements.

 Toast.makeText(context, Message, Toast.LENGTH_LONG);

so this should be:

    runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
    }
});

Alternatively you can use handler instead of thread

Handler handler=new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        try {
            //do some thing
        } catch (Exception e) {
            Toast.makeText(context, Message, Toast.LENGTH_LONG);
        } finally {
            //do work
        }
    }
}, 1000);   
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62