Skip to content Skip to sidebar Skip to footer

Method Settext Must Be Called From The Ui Thread

Have read all the set and get called from the UI thread, on stackoverflow but none seems relevent. this code worked 2years ago, recently opened it. and it shows this error. 'Method

Solution 1:

StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder() .detectAll().penaltyLog().build();     StrictMode.setThreadPolicy(policy);

That was actually turning off strict mode, which allowed unsafe things like updating the UI on non-UI threads and instead of crashing log it to disk. This isn't actually allowed anymore. So your code was always wrong, you were just ignoring the wrongness and hoping you wouldn't get caught. The correct fix is to move your code to the UI thread, and probably delete all mentions of StrictMode throughout your codebase- it should only be used as a debugging tool, and probably not even then.

And all the advice on not updating the UI from threads is absolutely relevant- you're setting the UI on an AsyncTask in doInBackground- so from another thread. Move that to the UI thread by either runOnUiThread, a handler, or by putting it off until onPostExecute or a progress message.

Solution 2:

You can not update UI from doInBackground in AsyncTask.

All UI related operations need to be done inside UI thread.

You can use runonUithread to update text in your textview inside doInBackground

Here is an example

Code:

@OverrideprotectedStringdoInBackground(String... arg0) {

    runOnUiThread(newRunnable() {
        @Overridepublicvoidrun() {
            grader.setText(informationTemp);
            vindhastighet.setText(informationVindhastighet);
            vindretning.setText(informationVindretning);

        }
    });

}

Or..better solution is to move your setText() code inside onPostExecute()

Solution 3:

You have to update UI from UI thread. As its not possible to update UI from doInBackground(), you can use runOnUiThread() to do update UI operations:

Try this:

@OverrideprotectedStringdoInBackground(String... arg0) {

    ...........
    ...................

    runOnUiThread(newRunnable() {
        @Overridepublicvoidrun() {
            grader.setText(informationTemp);
            vindhastighet.setText(informationVindhastighet);
            vindretning.setText(informationVindretning);

        }
    });

    .............
    .....................
}

Post a Comment for "Method Settext Must Be Called From The Ui Thread"