OkHttp, Android - download a html page and display this content in a view

浪子不回头ぞ 提交于 2019-12-06 13:49:36

I understood my error, I have to put my code into runOnUThread(). Thank you for your quick response ;)

Here my correction:

            package blabla.test;

            import android.support.v7.app.AppCompatActivity;
            import android.os.Bundle;
            import android.util.Log;
            import android.widget.TextView;

            import java.io.IOException;

            import okhttp3.Call;
            import okhttp3.Callback;
            import okhttp3.OkHttpClient;
            import okhttp3.Request;
            import okhttp3.Response;


            public class MainActivity extends AppCompatActivity {

                @Override
                protected void onCreate(Bundle savedInstanceState)  {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);

                    String url = "http://square.github.io/okhttp/";
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();

                    client.newCall(request).enqueue(new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("APp", e.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {

                                final String aFinalString = response.body().string();

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        TextView aff = (TextView) findViewById(R.id.aff);
                                        aff.setText(aFinalString);
                                    }
                                });

                            } else {
                                Log.e("APp", "Error");
                            }
                        }
                    });
                }
            }

The problem is simple enough. When you query is complete you do not update the TextView so as to display the needed information. Therefore it keeps its original message which is "error", defined in the activity_main.xml layout file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!