0

I have a txt file at the online storage that my university offers me and I want to read it at an android application. I've managed to do this in Java but when I try to do this in Android nothing happens. The Eclipse suggestions changes the code and nothing works. Please help me I am new to android development.

The a.txt file has content: This is a message!

This is the java code:

import java.io.*;
import java.net.*;

public class Java_Parser {    

        public static void main(String[] args) throws Exception {

            URL oracle = new URL("http://cgi.di.uoa.gr/~std10108/a.txt");
            BufferedReader in = new BufferedReader(
            new InputStreamReader(oracle.openStream()));

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

And the output is, as it should be : This is a message!

I have added the internet permission to the manifest so it's not the problem. I copy paste it in a function on an android project and after the suggestions of Eclipse it turns to this:

//This a function called when a button is clicked
 public void OnClick(View view){


        URL oracle = null;
         BufferedReader in = null;
 String inputLine;

         String text=null;

        try {
            oracle = new URL("http://cgi.di.uoa.gr/~std10108/a.txt");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            in = new BufferedReader(
            new InputStreamReader(oracle.openStream()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        try {
            while ((inputLine = in.readLine()) != null)
                text=text + inputLine;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        EditText edittext= (EditText) findViewById(R.id.editText1);
        edittext.setText(text);

    }

The application compiles succesfully but when I try to run it and click the button, it crashes. Can you help me?

This is the logcat

> 11-20 17:40:04.089: I/Process(9926): Sending signal. PID: 9926 SIG: 9
> 11-20 17:50:37.009: D/libEGL(10534): loaded
> /system/lib/egl/libEGL_mali.so 11-20 17:50:37.014: D/libEGL(10534):
> loaded /system/lib/egl/libGLESv1_CM_mali.so 11-20 17:50:37.014:
> D/libEGL(10534): loaded /system/lib/egl/libGLESv2_mali.so 11-20
> 17:50:37.024: D/(10534): Device driver API match 11-20 17:50:37.024:
> D/(10534): Device driver API version: 10 11-20 17:50:37.024:
> D/(10534): User space API version: 10  11-20 17:50:37.024: D/(10534):
> mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST
> 2012  11-20 17:50:37.054: D/OpenGLRenderer(10534): Enabling debug mode
> 0 11-20 17:50:39.449: D/AndroidRuntime(10534): Shutting down VM 11-20
> 17:50:39.449: W/dalvikvm(10534): threadid=1: thread exiting with
> uncaught exception (group=0x416d22a0) 11-20 17:50:39.454:
> E/AndroidRuntime(10534): FATAL EXCEPTION: main 11-20 17:50:39.454:
> E/AndroidRuntime(10534): java.lang.IllegalStateException: Could not
> execute method of the activity 11-20 17:50:39.454:
> E/AndroidRuntime(10534):  at
> android.view.View$1.onClick(View.java:3704) 11-20 17:50:39.454:
> E/AndroidRuntime(10534):  at
> android.view.View.performClick(View.java:4232) 11-20 17:50:39.454:
> E/AndroidRuntime(10534):  at
> android.view.View$PerformClick.run(View.java:17318) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> android.os.Handler.handleCallback(Handler.java:615) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> android.os.Handler.dispatchMessage(Handler.java:92) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> android.os.Looper.loop(Looper.java:137) 11-20 17:50:39.454:
> E/AndroidRuntime(10534):  at
> android.app.ActivityThread.main(ActivityThread.java:4921) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> java.lang.reflect.Method.invokeNative(Native Method) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> java.lang.reflect.Method.invoke(Method.java:511) 11-20 17:50:39.454:
> E/AndroidRuntime(10534):  at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
> 11-20 17:50:39.454: E/AndroidRuntime(10534):  at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> dalvik.system.NativeStart.main(Native Method) 11-20 17:50:39.454:
> E/AndroidRuntime(10534): Caused by:
> java.lang.reflect.InvocationTargetException 11-20 17:50:39.454:
> E/AndroidRuntime(10534):  at
> java.lang.reflect.Method.invokeNative(Native Method) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> java.lang.reflect.Method.invoke(Method.java:511) 11-20 17:50:39.454:
> E/AndroidRuntime(10534):  at
> android.view.View$1.onClick(View.java:3699) 11-20 17:50:39.454:
> E/AndroidRuntime(10534):  ... 11 more 11-20 17:50:39.454:
> E/AndroidRuntime(10534): Caused by:
> android.os.NetworkOnMainThreadException 11-20 17:50:39.454:
> E/AndroidRuntime(10534):  at
> android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
> 11-20 17:50:39.454: E/AndroidRuntime(10534):  at
> java.net.InetAddress.lookupHostByName(InetAddress.java:385) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> java.net.InetAddress.getAllByName(InetAddress.java:214) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> libcore.net.http.HttpConnection.<init>(HttpConnection.java:70) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> libcore.net.http.HttpConnection.<init>(HttpConnection.java:50) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
> 11-20 17:50:39.454: E/AndroidRuntime(10534):  at
> libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
> 11-20 17:50:39.454: E/AndroidRuntime(10534):  at
> libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
> 11-20 17:50:39.454: E/AndroidRuntime(10534):  at
> libcore.net.http.HttpEngine.connect(HttpEngine.java:310) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
> 11-20 17:50:39.454: E/AndroidRuntime(10534):  at
> libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    at
> libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
> 11-20 17:50:39.454: E/AndroidRuntime(10534):  at
> libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
> 11-20 17:50:39.454: E/AndroidRuntime(10534):  at
> java.net.URL.openStream(URL.java:462) 11-20 17:50:39.454:
> E/AndroidRuntime(10534):  at
> com.example.test.MainActivity.OnClick(MainActivity.java:55) 11-20
> 17:50:39.454: E/AndroidRuntime(10534):    ... 14 more

Edit1: I added the Internet permission but nothing changed

4
  • Get the stacktrace of the crash from logcat and edit your question to include that. My guess is that you didn't include the internet permission for your app Commented Nov 20, 2013 at 15:52
  • may be the server refused the connection. post your stacktrace to the question Commented Nov 20, 2013 at 15:53
  • Sry but I am new to android and this may be a silly question: What is the stacktrace and how can I access it? Commented Nov 20, 2013 at 15:55
  • A stacktrace is not specific to android but to java. It's the whole text after the words "FATAL EXCEPTION" in your logcat. Commented Nov 20, 2013 at 15:59

5 Answers 5

1

Add this code in the onCreate method :-

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

ADD this to ManiFestFile:

<uses-permission android:name="android.permission.INTERNET"/>
Sign up to request clarification or add additional context in comments.

5 Comments

While this will fix his problem, it is poor practice to run network calls on the UI thread.
It's already been posted as an answer. Using AsyncTask is the route to go.
Good. Till the asker has tick marked the useful answer, i think i can post answers. This is also a solution but lazy. I know
It works. Since it one of my firsts apps I will leave it this way. But I will try to learn how to use AsyncTask
Yes , you do that. It is a better approach
1

Your issue is rooted in this exception: android.os.NetworkOnMainThreadException

The android system protects long blocks on using the Internet during the UI thread to prevent apps from becoming unresponsive. To properly download a file on the main thread you'll want to use some sort of Asynchronous thread to download the file and do a callback to the main thread to process it.

Start with looking into the AsyncTask here or searching for the exception itself on this site to help find numerous examples.

1 Comment

Just for information it's better to declare a thread that handles this job?
0

Have you set the correct permissions in the AndroidManifest.xml? For example, the android.permission.INTERNET permission would be required:

public static final String INTERNET. Allows applications to open network sockets. Constant Value: "android.permission.INTERNET"

For debugging purposes, it may be easy to just pack all the code in one try-catch statement, as is being done below:

try {
    URL oracle = new URL("http://cgi.di.uoa.gr/~std10108/a.txt");
    BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
} catch (Exception e) {
    e.printStackTrace();
}

2 Comments

The thing everyone forgets at least once in his life when working on Android apps: the android.permission.INTERNET :P
I change it but the string now is empty. Not a single character is read
0

oracle.openConnection.getInputStream() would fit better ..

Comments

0

You can use a PHP file on your server to display it.

First, you have to create an webview.

On the PHP file write the following code:

<!doctype html>
<html xmlns="http://w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="Cache-Control" content="no-Cache" />
    <title>Somewhat</title>
    <style type="text/css">body {font-family: sans-serif;}</style>
</head>

<body>
    <?php
      $yourfile = fopen("path/to/file.txt", "r");
      $contentoffile = fread($yourfile, 1024);
      fclose($yourfile);
    ?>
    <p><?php echo $contentoffile; ?></p>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.