Java – Downloading txt files crashes the application

Downloading txt files crashes the application… here is a solution to the problem.

Downloading txt files crashes the application

I tried to download a file from the internet with this method :

try { 
    URL url = new URL("http://sites.google.com/site/androidersite/text.txt");
    BufferedReader in =new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {  newline character(s)
    }  
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
} 

I also updated my Android Manifest and added the following line:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

The app crashes on this line:

BufferedReader in =new BufferedReader(new InputStreamReader(url.openStream()));

And a log file pops up that says: Source not found

Solution

Is this code running on the main application thread? Which version of Android are you using for testing? If it’s on the main (UI) thread, that’s not good. It may throw “network on main thread” exceptions because they prevent you from doing so 🙂

Can you provide some actual logcat output of the crash, or maybe more context for the code being executed?

Related Problems and Solutions