1

I know this question has been asked a lot on SO already so I apologize if it is redundant, but I can't seem to find an answer to my specific problem anywhere.

I'm attempting to connect my Android emulator to a localhost. Here is my connection code:

public void readPHP(String filename) throws IOException {
        url = new URL("http://10.0.2.2:8000/" + filename);
        URLConnection conn = url.openConnection();
        InputStream stream = null;
        try {
            stream = conn.getInputStream();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        // more code....

        stream.close();
    }

I've also added the following line to my manifesto:

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

The app installs properly with no error messages but when I try to run it from the phone, it crashes with the vague message "Unfortunately, CodeGlass GDK has stopped." I'm sure this is a problem with Android because when I try to run the same code in a simple Java program it works as expected.

Will Stone
  • 15
  • 3

2 Answers2

0

You are opening a connection in your UI Thread, which is causing an NetworkOnMainThreadException . Just put your code inside an AsyncTask, inside doInBackground() method, like this:

public class MyAsyncTask extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(String fileName) {
      url = new URL("http://10.0.2.2:8000/" + filename);
        URLConnection conn = url.openConnection();
        InputStream stream = null;
        try {
            stream = conn.getInputStream();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        // more code....

        stream.close();
        return null;
     }
}
joao2fast4u
  • 6,868
  • 5
  • 28
  • 42
0

You must use asynctask to get the data from url like they said. But there is another way. İt is not advisable normally, but if you want to move on for now and get back and properly write an asynctask, you can use this piece of code for now;

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

Hope this helps.