0

Am new in android .. am trying to implement thread in a android. But am getting error .. I googled and getting answer "AsyncTask", but truly i dont know how to implement

Error message

 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

my code

final Thread thread = new Thread(){
                        @Override
                            public void run() {
                            try {
                                DatabaseHandler dbh = new DatabaseHandler(test.this);
                                result=dbh.Verify(1);
                                if(result != ""){

                                    getData();
                                    progress.dismiss();

                                }
                                else{


                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    thread.start();
  • Use ASyncTask, that is the solution for you and it is very easy to implement there are bunch of samples out there. – Prakash Nadar Apr 27 '13 at 05:49
  • You are not allowed to perform UI operation on non UI thread, so you need to do is `1. Create a handler and use hanlder.post()` method to update the UI or use `runOnUIthread`, search in google about the same – Pragnani Apr 27 '13 at 05:54

2 Answers2

0

Use following code to run in UI thread.

Runnable runnable = new Runnable() {
            @Override
            public void run() {
                handler.post(new Runnable() { // This thread runs in the UI
                    @Override
                    public void run() {
                       DatabaseHandler dbh = new DatabaseHandler(test.this);
                            result=dbh.Verify(1);
                            if(result != ""){

                            getData();
                            progress.dismiss();

                        }
                        else{


                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    };
    new Thread(runnable).start();
Hardik Joshi
  • 9,477
  • 12
  • 61
  • 113
0

Seems like you need to create your handler in MainActivity and then pass it further. Like so:

private Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    handler = new Handler();
}
Eugene
  • 117,005
  • 15
  • 201
  • 306