gsfd
gsfd

Reputation: 1070

Can someone fix my CalledFromWrongThreadException?

I have an activity that starts and then creates a new instance of NetworkHandler, in NetworkHandler i run it on a new thread so that the UI thread doesn't get stuck. The NetworkHandler has a run() method that sits on while((message = reader.readLine())!=null). reader is a BufferedReader and message is a String. Then the UI thread goes and does the layout. When the user navigates to the login screen and clicks the login button, the client sends a message to the server and receives information back, ie wither or not the username/password combination was correct. Then the thread that does the stream reading (the while loop) goes and tries to change the layout so that the game screen pops up if the login was successful or the oops you screwed something up screen. It gives me this annoying exception and it doesn't change the layout. Ive had this issue before in android, I don't understand why you have to call a View change from the UI Thread. It doesn't make sense to me. In Java i know that you can do that, i have make probably a hundred applications for my computer and i know that java doesn't have this issue. Can someone explain? All relevant answers are appreciated!

Upvotes: 0

Views: 151

Answers (3)

JBM
JBM

Reputation: 2962

Use Handler.post(...) to switch to the UI thread when you're about to update the layout. Like this:

private Handler myHandler;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myHandler = new Handler();
}

public void loadInBackround() {
    while(...) {
        // do stuff
    }
    final result = ....; 
    myHandler.post(new Runnable() {
            @Override
            public void run() {
                // update the layout with data from 'result'
                ...
            }
        });
}

Note that result has final modifier - it is required for accessing it from inside the Runnable. Also note that handler itself must be created on UI thread, e.g. in onCreate.

Upvotes: 1

pqn
pqn

Reputation: 1532

An AsyncTask can be used to conveniently run certain tasks on the UI Thread from a task on a different thread with its onProgressUpdate and onPostExecute methods.

Upvotes: 1

Amandeep Grewal
Amandeep Grewal

Reputation: 1821

http://developer.android.com/resources/articles/painless-threading.html

When an application is launched, the system creates a thread called "main" for the application. The main thread, also called the UI thread, is very important because it is in charge of dispatching the events to the appropriate widgets, including drawing events. It is also the thread where your application interacts with running components of the Android UI toolkit.

Upvotes: 0

Related Questions