my app crashes when trying to get a remote txt file. even if just try to parse a url it crashes. internet permission is set and the device/vm has connection to the internet.
LogCat:
code snippet:
try {
// the following line is enough to crash the app
URL url = new URL("http://www.i.am/not/going/to/show/you/this.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = null;
while ((line = in.readLine()) != null) {
//get lines
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
i don't inderstand what i'm doing wrong. thanks for help in advance.
//edit: added log cat snippet
The application is crashing due to heavy network activity on the main UI thread, which itself is not a very good practice, as the application can stop responding and might get killed by the OS. You should always try to do your background processing in some separate thread, and not on the main UI thread.
Put your code to fetch the file inside the
doInBackground()
of an AsyncTask.You can make a call to this task to fetch the file by
new DownloadFile().execute("");
where ever you would you want to get the file.