//Only the original thread that created a view hierarchy can touch its views. //Cannot update UI in non-UI thread
public class MainActivity extends AppCompatActivity { private Handler handler; @BindView(R.id.get_btn) Button get_btn; @BindView(R.id.post_btn) Button post_btn; @BindView(R.id.result_view) TextView result_view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); //handler of the main thread handler = new Handler (); } @OnClick(R.id.get_btn) public void getMsg(){ doGet(); } @OnClick(R.id.post_btn) public void postMsg(){ } public void doGet(){ //Create okhttpClient object OkHttpClient okhttpClient = new OkHttpClient(); //build Request Request.Builder builder = new Request.Builder(); Request request = builder.get().url("https://www.baidu.com").build(); //Encapsulate Request as Call Call call = okhttpClient.newCall(request); //Execute Call //Asynchronous execution provides callback interface call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Toast.makeText(MainActivity.this, "The network is not good", Toast.LENGTH_SHORT).show(); } @Override public void onResponse(Call call, Response response) throws IOException { final String string = response.body().string(); // Only the original thread that created a view hierarchy can touch its views. //result_view.setText(string); new Thread(){ @Override public void run() { handler.post(new Runnable() { @Override public void run() { result_view.setText(string); } }); } }.start(); } }); } }