killertoge killertoge - 4 months ago 15
Android Question

Android - How can I read a text file from a url?

I uploaded a text file(*.txt) to a server, now I want to read the text file...

I tried this example without luck.

ArrayList<String> urls=new ArrayList<String>(); //to read each line
TextView t; //to show the result
try {
// Create a URL for the desired page
URL url = new URL("mydomainname.de/test.txt"); //My text file location
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

t=(TextView)findViewById(R.id.TextView1);
String str;
while ((str = in.readLine()) != null) {
urls.add(str);


}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
t.setText(urls.get(0)); // My TextFile has 3 lines


App is closing itself...
Can it be up to the domain name ? Should there be a IP instead ?
I figured out that the while loop isn't executed.
Because if I put t.setText* in the while loop there is no error, and the TextView is empty.
LogCat Error : http://textuploader.com/5iijr it highlight the line with
t.setText(urls.get(0));


Thanks in Advance !!!

Answer

Try using an HTTPUrlConnection or a OKHTTP Request to get the info, here try this:

Always do any kind of networking in a background thread else android will throw a NetworkOnMainThread Exception

new Thread(new Runnable(){

  public void run(){


    ArrayList<String> urls=new ArrayList<String>(); //to read each line
    //TextView t; //to show the result, please declare and find it inside onCreate()



    try {
         // Create a URL for the desired page
         URL url = new URL("http://somevaliddomain.com/somevalidfile"); //My text file location
         //First open the connection 
         HttpURLConnection conn=(HttpURLConnection) url.openConnection();
         conn.setConnectTimeout(60000); // timing out in a minute

         BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

         //t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()
        String str;
        while ((str = in.readLine()) != null) {
            urls.add(str);
        }
        in.close();
    } catch (Exception e) {
        Log.d("MyTag",e.toString());
    } 

    //since we are in background thread, to post results we have to go back to ui thread. do the following for that

    Activity.this.runOnUiThread(new Runnable(){
      public void run(){
          t.setText(urls.get(0)); // My TextFile has 3 lines
      }
    });

  }
}).start();
Comments