mercredi 25 février 2015

NetworkOnMainThreadException but Using AsyncTask



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.




Aucun commentaire:

Enregistrer un commentaire