Reputation: 297
I coded a class which starts a http connection for getting the text of e.g. website. I used AsyncTask but I got NetworkOnMainException. May u help me? The class
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;
}
Here how I start the AsyncTask:
bu_aktualize.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_getXMLData.doInBackground("http://www.google.de");
}
});
Thanks for your help.
Upvotes: 0
Views: 53
Reputation: 1007584
You do not call doInBackground()
yourself. Instead, you call execute()
or executeOnExecutor()
to start the AsyncTask
.
You may wish to review the documentation for AsyncTask
, which shows an example of setting up an AsyncTask
, including a call to execute()
.
Upvotes: 5