我想要下載一個html頁面以便在TextView中顯示一些信息。每次,我的程序都會在TextView中顯示「錯誤」。爲什麼我的程序不工作?OkHttp,Android - 下載一個html頁面並在視圖中顯示此內容
我在AndroidManifest.xml文件中添加這一行:
<uses-permission android:name="android.permission.INTERNET" />
這裏我activity_main.xml中的文件:
<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingbottom="@dimen/activity_vertical_margin"
android:paddingleft="@dimen/activity_horizontal_margin"
android:paddingright="@dimen/activity_horizontal_margin"
android:paddingtop="@dimen/activity_vertical_margin"
tools:context="blabla.test.mainactivity">
<textview
android:id="@+id/aff"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="error" />
</relativelayout>
在這裏,我MainActivity.java:
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 {
public static String test = "error";
@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()) {
MainActivity.test = response.body().string();
}else{
Log.e("APp", "Error");
}
}
});
TextView aff = (TextView) findViewById(R.id.aff);
aff.setText(MainActivity.test);
}
}
我提前感謝您的幫助:)
事實上,你應該把'TextView的AFF =(TextView的)findViewById(R.id.aff); aff.setText(MainActivity.test);'進入你的'onResponse'我想。 – hervinhio
@Mammouth結果如何? – hervinhio
我得到了'致命的例外:OkHttp Dispatcher'並且程序關閉了。 – Mammouth