0

Possible Duplicate:
android.os.NetworkOnMainThreadException

I want to open a text file (one line with a few words) from a server in a TextView, but my current code crashes the app when I open the activity. I've tried:

urlTextOut = (TextView) findViewById(R.id.URLtextView); 
StringBuilder text = new StringBuilder();

try {
    String str = "";
    URL url = new URL("http://mysite.com/text1.txt");

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

    while ((str = in.readLine()) != null) {
         text.append(str);
    }
    in.close();
} catch (MalformedURLException e1) {
} catch (IOException e) {
}

urlTextOut.setText(text);

I've also tried something very similar to this: How to read text file in android from web? (with added try/catches where it wanted them) but that also crashed the app. I've tried looking at Apache's HttpComponents but couldn't figure out what I was meant to do with the downloaded zip file.

Community
  • 1
  • 1
user1260239
  • 1
  • 1
  • 2

1 Answers1

0

You're probably getting a NetworkOnMainThreadException. Android will not allow you to make network calls on the main/UI thread (ie directly in your Activity). You should use a separate thread, see this question for an example.

Community
  • 1
  • 1
Sam Dozor
  • 40,335
  • 6
  • 42
  • 42
  • Thanks, that is what's going wrong! I'm a bit confused about the AsyncTask class - it has a problem with the word RSSFeed in 'AsyncTask' and 'protected RSSFeed doInBackground'. I tried changing the second to String since I'm using Strings not RSSFeeds, but it didn't help. – user1260239 Mar 09 '12 at 22:53