Skip to content Skip to sidebar Skip to footer

Updating Ui / Runonuithread / Final Variables: How To Write Lean Code That Does Ui Updating When Called From Another Thread

I have been reading up on the UI updating when I found out that, like WinForms, Android need to do UI updates on from the main thread (too bad, I was hoping someone could once and

Solution 1:

Try it:

@OverridepublicvoidconnStateChange(ClientHandler clientHandler) {
    finalClientHandlertemporaryHander= clientHandler;
    runOnUiThread(newRunnable() {
         publicvoidrun() {
               tv.append(temporaryHandler.getIP() + ", " + temporaryHandler.state.toString() + "\n"); 
               if (temporaryHandler.state == State.Connected) {
                    tv.append("Loginserver hittad");         
               }       
         }    
    }); 
} 

By the way, code becomes more readable, if you declare not anonim class right in the method, but declare inner class out of methods. Consider it as pattern Command.

Example of more clean and reusable code.

@OverridepublicvoidconnStateChange(ClientHandler clientHandler) {
    finalClientHandlertemporaryHander= clientHandler;
    runOnUiThread(newMyRunnableCommand(temporaryHandler)); 
} 

privateclassMyRunnableCommandimplementsRunnable { 

     private ClientHandler clientHandler;

     publicMyRunnableCommand(ClientHandler clientHandler) {
         this.clientHandler = clientHandler;
     }

     @Overridepublicvoidrun() {
               tv.append(clientHandler.getIP() + ", " + clientHandler.state.toString() + "\n"); 
               if (clientHandler.state == State.Connected) {
                    tv.append("Loginserver hittad");         
               }       
         } 

}

Though the Runnable implementation itself was inflated a little, code became more re-usable and easy to read.

Post a Comment for "Updating Ui / Runonuithread / Final Variables: How To Write Lean Code That Does Ui Updating When Called From Another Thread"