1

In android, some codes, such as updating UI buttons, needs to be called in UI thread, however, before UI update, some task, such as getting response from internet, need to be done on another thread, here is the most common form of response callback I see:

public void httpResponseCallback(String responseString){
    MyFragment.this.getActivity().runOnUiThread(new Runnable(){
        @Override
        public void run(){
            if(responseString==null || responseString.isEmpty()){
                showErrorDialog();
            }else{
                List<String> nameList=this.parse(responseString);
                if(nameList==null){
                    showErrorDialog();
                }else{
                    updateUI(nameList);
                }
            }
        }
    });
}

But I think this callback is not good enough, because some codes doesn't require to place inside runOnUiThread, so I think the following form is better:

public void httpResponseCallback(String responseString){
    if(responseString==null || responseString.isEmpty()){

        MyFragment.this.getActivity().runOnUiThread(new Runnable(){
            @Override
            public void run(){
                showErrorDialog();
        }
        });
    }else{
        final List<String> nameList=this.parse(responseString);
        if(nameList==null){

            MyFragment.this.getActivity().runOnUiThread(new Runnable(){
            @Override
            public void run(){
                showErrorDialog();
            }
        });
        }else{

            MyFragment.this.getActivity().runOnUiThread(new Runnable(){
            @Override
            public void run(){
                updateUI(nameList);
            }
        }
    }
}

After refactoring, at start, I think it would be more logical because:

  1. It reduce unnecessary workload on UI thread
  2. It give hints to other teammates that which functions or codes need to run on UI thread

But later when I read the code again, I found the code is far longer than the original one because of extra runOnUiThread to type, so my question is, is wrapping all codes into runOnUiThread better than using runOnUiThread only on UI related code?

  • 2
    Where do you stop? What if showErrorDialog or updateUI also contain code that doesn't need to execute in the UI thread? – Bart van Ingen Schenau May 16 '17 at 6:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.