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
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:
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:
Please note that AsyncTask is deprecated in API level 30 and higher. For modern Android development, c
enter code here
onsider 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.For reference, use the URL#openStream method.