0

Hello I am working with an android application and i am trying to change the screen inside a thread and i get the following error "Only the original thread that created a view hierarchy can touch its views" Please check at my code and tell me a way to overcome this error

 Runnable runnable = new Runnable() {
        public void run() {
            Users user = mapper.load(Users.class,username);

            System.out.println(user.getPassword());
            System.out.println(username);
            if (user != null && user.getPassword().equals(password)){
                //System.out.println("Correct");

                setContentView(R.layout.activity_account);
            }
Umair Ayaz
  • 27
  • 1
  • 8

3 Answers3

1

You can use runOnUiThread:

runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            setContentView(R.layout.activity_account);
                        }
                    });
Chol
  • 2,097
  • 2
  • 16
  • 26
0

You can use runOnUIThread() - see docs

Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

runOnUiThread(new Runnable() {
   @Override
   public void run() {
       setContentView(R.layout.activity_account);
    }
});
Ed Holloway-George
  • 5,092
  • 2
  • 37
  • 66
0

You have to do on UIThread like below:

 new AsyncTask<Void, Void, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... params) {
            Users user = mapper.load(Users.class,username);

            System.out.println(user.getPassword());
            System.out.println(username);
            return user != null && user.getPassword().equals(password);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result){
                setContentView(R.layout.activity_account);
            }
        }
    }.execute();
Akbar
  • 430
  • 4
  • 18