Thahzan
Thahzan

Reputation: 1005

Android : CalledFromWrongThreadException even when used runOnUIThread

I'm building an application which sends login data and authenticates by communicating with the php files in my localhost (referring to this tutorial http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/). I tried it like the tutorial says (in the main thread) but it gives a NetworkOnMainThreadException. But when I try the following inside an AsyncTask, it gives a CalledFromWrongThreadException even when I'm using runOnUIThread.

@Override
        protected Void doInBackground(Void... arg0) {

            String username = etUsername.getText().toString();
            String password = etPass.getText().toString();
            UserFunctions userFunctions = new UserFunctions();
            final JSONObject json = userFunctions.loginUser(username, password);

            try {
                if (json.getString(KEY_SUCCESS) != null) {

                    String res = json.getString(KEY_SUCCESS);
                    if (Integer.parseInt(res) == 1) {
                        // user successfully logged in
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                errorTxt.setText("");
                                //if (pDialog.isShowing())
                                    //pDialog.dismiss();
                                Intent intent = new Intent(
                                        getApplicationContext(),
                                        AgentHome.class);
                                startActivity(intent);
                            }
                        });

                    }
                } else if(json.getString(KEY_ERROR) != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //if (pDialog.isShowing())
                                //pDialog.dismiss();
                            errorTxt.setText("Invalid username or password");
                        }
                    });

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

Edit : I put the errorTxt.setText("") inside the runOnUIThread but still it gives the following errors

02-11 10:27:20.397: E/AndroidRuntime(4957): FATAL EXCEPTION: AsyncTask #1
02-11 10:27:20.397: E/AndroidRuntime(4957): Process: collector.lbfinance, PID: 4957
02-11 10:27:20.397: E/AndroidRuntime(4957): java.lang.RuntimeException: An error occured while executing doInBackground()
02-11 10:27:20.397: E/AndroidRuntime(4957):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
02-11 10:27:20.397: E/AndroidRuntime(4957):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
02-11 10:27:20.397: E/AndroidRuntime(4957):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
02-11 10:27:20.397: E/AndroidRuntime(4957):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
02-11 10:27:20.397: E/AndroidRuntime(4957):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-11 10:27:20.397: E/AndroidRuntime(4957):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-11 10:27:20.397: E/AndroidRuntime(4957):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-11 10:27:20.397: E/AndroidRuntime(4957):     at java.lang.Thread.run(Thread.java:841)
02-11 10:27:20.397: E/AndroidRuntime(4957): Caused by: java.lang.NullPointerException
02-11 10:27:20.397: E/AndroidRuntime(4957):     at collector.lbfinance.MainActivity$GetPassword.doInBackground(MainActivity.java:108)
02-11 10:27:20.397: E/AndroidRuntime(4957):     at collector.lbfinance.MainActivity$GetPassword.doInBackground(MainActivity.java:1)
02-11 10:27:20.397: E/AndroidRuntime(4957):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-11 10:27:20.397: E/AndroidRuntime(4957):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-11 10:27:20.397: E/AndroidRuntime(4957):     ... 4 more

Upvotes: 2

Views: 260

Answers (4)

i.n.e.f
i.n.e.f

Reputation: 1803

First of all You are Setting text in background Thread Which is wrong & it gives u exception so first remove that errorTxt.setText(""); from doInBackground & set that in PreExecute Or PostExecute or In Some another UI thread But not in Background. And No need to use this

 runOnUiThread(new Runnable() {} 

Thread, If you write your code in Background Async Task then also it will work same. hope this helps.

Upvotes: 0

Lavekush
Lavekush

Reputation: 6166

Please use hanlder and pass your response to handler, it will work.

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

Handler Docs

Handler example

Upvotes: 0

Sam
Sam

Reputation: 1662

Check AsyncTask lifecycle. You can execute code on UI thread in constructor and following methods: onPreExecute, onProgressUpdate(with corresponding publishProgress call) and onPostExecute. Be sure to place your UI changing code to one of those

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

errorTxt.setText(""); is not on the ui thread. You can't update ui from a background thread.

Also you can get the text from edittext on button click and pass it as a param to doInBackground directly.

Asynctask has onPreExecute and onPostExecute which are invoked on the ui thread. You should consider updating ui in those methods. Do all your background computation in doInbackground. I don't see the need for runOnUiThread.

Upvotes: 1

Related Questions