我想将网页上的文字放到Android 3.0上的textview中。我有这段代码:
public class Biografie extends Activity {
private TextView outtext;
private String HTML;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biografie);
outtext= (TextView) findViewById(R.id.textview1);
try {
getHTML();
} catch (Exception e) {
e.printStackTrace();
}
outtext.setText("" + HTML);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.biografie, menu);
return true;
}
private void getHTML() throws ClientProtocolException, IOException
{
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://artistone.appone.nl/api/biografie.php?dataid=998"); //URL!
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while ((line = reader.readLine()) != null) {
result += line + "\n";
HTML = result;
}
}
}
我的TextView返回“null”而不是页面中的文本。请帮我解决这个问题。谢谢。
答案 0 :(得分:0)
将您的代码更改为:
while ((line = reader.readLine()) != null) {
result += line + "\n";
}
HTML = result;
试试这个:
outtext.setText(Html.fromHtml(HTML));
而不是在主线程中执行网络操作,我建议您使用AsyncTask
答案 1 :(得分:0)
问题是你得到NetworkOnMainThreadException
那是因为您正在主线程(活动线程)上下载网络内容。
相反,您需要使用后台线程下载该内容,或使用 AsynchTask 。
应该解决此问题的简单代码:
final Handler handler = new Handler();
Thread thread = new Thread() {
public void run() {
try {
getHTML();
handler.post(new Runnable() {
@Override
public void run() {
outtext.setText("" + HTML);
}
});
} catch (Exception e) {
e.printStackTrace();
handler.post(new Runnable() {
@Override
public void run() {
outtext.setText(e.toString());
}
}
}
};
thread.start(); // I forgot to start the thread. sorry !
而不是:
try {
getHTML();
} catch (Exception e) {
e.printStackTrace();
}
outtext.setText("" + HTML);
另请参阅本教程关于android线程:Tutorial