sno*_*rot 0 java android android-asynctask
我编写了一个类,它启动一个http连接来获取例如网站的文本.我使用AsyncTask但我得到了NetworkOnMainException.你能救我吗?班级
public class getXMLData extends AsyncTask<String, Void, String> {
TextView _textview;
public getXMLData(TextView textview) {
_textview = textview;
}
protected String doInBackground(String... url)
{
String _text = "";
try {
try {
URL _url = new URL(url[0]);
HttpURLConnection con = (HttpURLConnection) _url.openConnection();
_text = readStream(con.getInputStream());
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
return _text;
}
protected void onPostExecute(String result)
{
_textview.setText(result.toCharArray(), 0, result.length());
}
private String readStream(java.io.InputStream in) {
java.io.BufferedReader reader = null;
String result = "";
reader = new BufferedReader(new InputStreamReader(in));
try {
while ((reader.readLine() != null)) {
result = result + reader.readLine();
}
}
catch (java.io.IOException i)
{
}
finally
{
try {
reader.close();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我在这里如何启动AsyncTask:
bu_aktualize.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_getXMLData.doInBackground("http://www.google.de");
}
});
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
你不打电话给doInBackground()自己.相反,你打电话execute()或executeOnExecutor()开始AsyncTask.
您可能希望查看文档AsyncTask,其中显示了设置的示例AsyncTask,包括对其的调用execute().
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |