views:

359

answers:

2

I have a text file on my server. I want to open the text file from my Android App and then display the text in a TextView. I cannot find any examples of how to do a basic connection to a server and feed the data into a String.

Any help you can provide would be appreciated.

+1  A: 

Try the following:

try {
    // Create a URL for the desired page
    URL url = new URL("mysite.com/thefile.txt");

    // Read all the text returned by the server
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
    }
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

(taken from Exampledepot: Getting text from URL)

Should work well on Android.

aioobe
+1  A: 

While URL.openStream will work, you would be better off using the Apache HttpClient library that comes with Android for HTTP. Among other reasons, you can use content encoding (gzip) with it, and that will make text file transfers much smaller (better battery life, less net usage) and faster.

There are various ways to use HttpClient, and several helpers exist to wrap things and make it easier. See this post for more details on that: http://stackoverflow.com/questions/874227/android-project-using-httpclient-http-client-apache-post-get-method (and note the HttpHelper I included there does use gzip, though not all do).

Also, regardless of what method you use to retrieve the data over HTTP, you'll want to use AysncTask (http://android-developers.blogspot.com/2009/05/painless-threading.html) to make sure not to block the UI thread while making the network call.

Charlie Collins