I am trying to retrieve data from a website and my app keeps crashing. I have located the issue down to the openStream() command. The class I am using is defined below. I am
NetworkOnMainThreadException
You created your own doInBackground methods, but Internet connection must be only in background, put your code to overrided methods doInbackground! See example below:
In background implement getting data, in method opPostExecute - settings data to views.
private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... arg0) {
URL url = null;
try {
url = new URL("URL is in here");
BufferedInputStream bis = new BufferedInputStream(url.openStream());
byte[] buffer = new byte[1024];
StringBuilder sb = new StringBuilder();
int bytesRead = 0;
while((bytesRead = bis.read(buffer)) > 0) {
String text = new String(buffer, 0, bytesRead);
sb.append(text);
}
bis.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return yourResult;
}
}
or
private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... arg0) {
doInBackground(); //your methods
return null;
}
protected void doInBackground() {
URL url = null;
try {
url = new URL("URL is in here");
BufferedInputStream bis = new BufferedInputStream(url.openStream());
byte[] buffer = new byte[1024];
StringBuilder sb = new StringBuilder();
int bytesRead = 0;
while((bytesRead = bis.read(buffer)) > 0) {
String text = new String(buffer, 0, bytesRead);
sb.append(text);
}
bis.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
hope, I help you.