3

I try to download 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 update my Android Manifest and add this lines:

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

and the app crash in this line :

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

and popup a log file that wrote: Source not found

YosiFZ
  • 7,792
  • 21
  • 114
  • 221

2 Answers2

2

Is this code running on the main application thread? What version of Android are you testing with? If it is on the main (UI) thread, that's bad. It may be throwing a "network on main thread" exception because they discourage you from doing that :)

Can you provide some actual logcat output from the crash, or possibly more context for the code that is executing?

lyricsboy
  • 2,999
  • 24
  • 21
  • Then you need to move that code to another thread. `AsyncTask` can be a good choice for this. Here is some documentation: http://developer.android.com/reference/android/os/AsyncTask.html There are also lots of examples around the web. – lyricsboy Feb 03 '12 at 15:50
2

Might be relevant

http://www.javahotchocolate.com/tutorials/android.html#notfound http://stackoverflow.com/questions/4720593/source-not-found-error-in-android

           /* Open a connection to that URL. */
           URLConnection ucon = url.openConnection();

           /*
            * Define InputStreams to read from the URLConnection.
            */
           InputStream is = ucon.getInputStream();
           BufferedInputStream bis = new BufferedInputStream(is);

Check here for example http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device

Dave
  • 121
  • 4