Junaid Noor
Junaid Noor

Reputation: 474

android: update UI from another thread in another class

The scenario is I have two threads and a UI thread. The UI thread when clicked on login button creates a ClientThread which creates a socket and runs until the socket is connected, whenever a message is received i use a handler to post message to another thread called ProcessDataThread, now on receiving some messages from server i need to update UI related stuff from ProcessDataThread, I searched around alot and i found these two ways runonUiThread function which i guess can only be run from the Activity Class which is useless and the Asynctask method which i am not sure how to pass the activity context to...

Here is the code

The code executed when clicked on Login Button in the MainActivity

public void onLoginClick(View view)
{
    global_constants.clientObject = new ClientThread();
    global_constants.clientThread = new Thread(global_constants.clientObject);
    global_constants.clientThread.start();
}

The code in ClientThread run method

public class ClientThread implements Runnable {
.......
    @Override
    public void run() {
    ......
        while(!Thread.currentThread().isInterrupted() && (!CloseThread))
        {
            byte[] buff;
            ....
            global_constants.updateConversationHandler.post(new ProcessDataThread(buff));
        }
    }
}

The method code in ProcessDataThread after parsing out the incoming data and stuff

public class ProcessDataThread implements Runnable {
.........
    void ProcessLoginFailedPacket(byte[] buff)
    {
        // how to call the UI thread from here for updating some UI elements??
    }
}

[EDIT]

i stored the activity context in a global variable and then did it this way, but i dont know whether it will be safer or not

((Activity)global_constants.MainContext).runOnUiThread(new Runnable(){
    public void run()
    {
        TextView txtErr = (TextView) ((Activity)global_constants.MainContext).findViewById(R.id.errMsg);
        txtErr.setVisibility(0);
        txtErr.setText(reason);
    } 
});

Upvotes: 1

Views: 7146

Answers (1)

keerthy
keerthy

Reputation: 236

You can post a runnable which does the UI operation to main thread as follows,

public class Utils {

    public static void runOnUiThread(Runnable runnable){
        final Handler UIHandler = new Handler(Looper.getMainLooper());
        UIHandler .post(runnable);
    } 
}

Utils.runOnUiThread(new Runnable() {
     @Override
     public void run() {
         // UI updation related code.
     }
});

Upvotes: 8

Related Questions