skip to Main Content

Android Studio – Java
I’ve been trying to read a text file from my website for days now.
The examples found on the internet don’t work.
"Error" is always output in the "catch" (see code below).
The path to the URL is correct. I tested it with a download.
Internet permission has been added.
Where is the problem?

 try{

            URL yahoo = new URL("https://www.robl.de/data/HS.txt");
            URLConnection yc = yahoo.openConnection();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            yc.getInputStream()));


            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
            in.close();

    }
    catch ( IOException e ) {
        e.printStackTrace();
        inputLine="error";
    }


 try{
        URL llll = new URL("http://www.robl.de/data/HS.txt");

        URLConnection conLLL = llll.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader( conLLL.getInputStream()));

        while ( ( strLine = br.readLine() ) != null)
            System.out.println(strLine);
        br.close();

    }
    catch(Exception ex)
    {
        ex.printStackTrace();
        strLine="error";
    }

2

Answers


  1. It sounds like you’re encountering a NetworkOnMainThreadException, which occurs when trying to perform a network operation on the Android UI thread. Android requires network requests to be made on a background thread. Here’s how you can modify your code to use an AsyncTask to perform the network operation on a background thread:

    import android.os.AsyncTask;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;
    
    public class NetworkFileReader extends AsyncTask<String, Void, String> {
    
        @Override
        protected String doInBackground(String... urlString) {
            StringBuilder content = new StringBuilder();
            try {
                URL url = new URL(urlString[0]);
                URLConnection urlConnection = url.openConnection();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    content.append(line).append("n");
                }
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
            return content.toString();
        }
    
        @Override
        protected void onPostExecute(String result) {
            // This is where you would handle the result of the network operation
            // For example, updating the UI or storing the data
            System.out.println(result);
        }
    }
    
    // Usage:
    new NetworkFileReader().execute("https://www.robl.de/data/HS.txt");
    

    Make sure to execute this AsyncTask appropriately in your activity or fragment, and handle the result in the onPostExecute method.

    Also, ensure that you have the internet permission in your AndroidManifest.xml:

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

    Please note that AsyncTask is deprecated in API level 30 and higher. For modern Android development, center code hereonsider using Kotlin coroutines or Java concurrency utilities like Executors. However, AsyncTask is still a valid way to quickly solve this problem for educational purposes or in legacy codebases.

    Login or Signup to reply.
  2. For reference, use the URL#openStream method.

    URL u = new URI("https://www.robl.de/data/HS.txt").toURL();
    try (BufferedReader r = new BufferedReader(new InputStreamReader(u.openStream()))) {
        r.lines().forEach(System.out::println);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search