Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

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 !!!

like image 256
killertoge Avatar asked Jul 14 '16 11:07

killertoge


3 Answers

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();
like image 99
Kushan Avatar answered Sep 27 '22 01:09

Kushan


1-) Add internet permission to your Manifest file.

2-) Make sure that you are launching your code in separate thread.

Here is the snippet which works for me great.

    public List<String> getTextFromWeb(String urlString)
    {
        URLConnection feedUrl;
        List<String> placeAddress = new ArrayList<>();

        try
        {
            feedUrl = new URL(urlString).openConnection();
            InputStream is = feedUrl.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));          
            String line = null;

            while ((line = reader.readLine()) != null) // read line by line
            {
                placeAddress.add(line); // add line to list
            }
            is.close(); // close input stream

            return placeAddress; // return whatever you need
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return null;
    }

Our reader function is ready, let's call it by using another thread

            new Thread(new Runnable()
            {
                public void run()
                {
                    final List<String> addressList = getTextFromWeb("http://www.google.com/sometext.txt"); // format your URL
                    runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            //update ui
                        }
                    });
                }
            }).start();
like image 24
Burak Cakir Avatar answered Sep 24 '22 01:09

Burak Cakir


just put it inside a new thread and start the thread it will work.

new Thread(new Runnable() 
    {
    @Override
    public void run()
    { 
    try
    {
    
    URL url = new URL("URL");//my app link change it
    
    HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
    String line;
    StringBuilder lin2 = new StringBuilder();
    while ((line = br.readLine()) != null) 
    {
    lin2.append(line);
    }
     Log.d("texts", "onClick: "+lin2);
    } catch (IOException e)
    {
    Log.d("texts", "onClick: "+e.getLocalizedMessage());
    e.printStackTrace();
    }
    }
    }).start();

thats it.

like image 24
Aishik kirtaniya Avatar answered Sep 25 '22 01:09

Aishik kirtaniya