0

Possible Duplicate:
Android HttpClient : NetworkOnMainThreadException

I have a php script on a server that recieves get requests, and mails out the content. So lets say we have http://url.com/testmail.php?message=somemessage

the contents of "message" will be sent in an email.

I want my app to be able to call this script, and insert it's own mesage in the request. It will mostly be used for user feedback. I know it would be better to use POST, and if there is some android function that can natively handle mail, please enlighten me as I am new.

This is the code I have at the moment inside my main activities "onCreate", and it is generating exceptions:

HttpClient httpClient = new DefaultHttpClient();  
    String url = "http://someurl/testmail.php?message=eventualjavavariable";
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            entity.writeTo(out);
            out.close();
            String responseStr = out.toString();
            // do something with response 
        } else {
            // handle bad response
        }
    } catch (ClientProtocolException e) {
        // handle exception
    } catch (IOException e) {
        // handle exception
    }

I also have added this line in my Android Manifest file:

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

What am I doing wrong?

This is my LogCat:

10-09 15:12:33.185: E/AndroidRuntime(5561): java.lang.RuntimeException: Unable to start activity    ComponentInfo{com.example.android.fragments/com.example.android.fragments.MainActivity}: android.os.NetworkOnMainThreadException
10-09 15:12:33.185: E/AndroidRuntime(5561):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-09 15:12:33.185: E/AndroidRuntime(5561):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-09 15:12:33.185: E/AndroidRuntime(5561):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-09 15:12:33.185: E/AndroidRuntime(5561):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
Community
  • 1
  • 1
Ryan
  • 433
  • 1
  • 11
  • 29

3 Answers3

1

The application is crashing due to network activity on the main UI thread, which itself is not a very good practice, as the application can stop responding and might get killed by the OS. You should always try to do your background processing in some separate thread, and not on the main UI thread.

You need to make the HttpConnection on a background thread, maybe by using an AsyncTask.

Swayam
  • 16,294
  • 14
  • 64
  • 102
  • so if I move this to another method it will work? I have a "feedback" method that this will eventually be in anyway – Ryan Oct 09 '12 at 19:37
  • Well, this coed needs to be shifted to a function which runs on the background non-Ui thread. The best option is to use `doInBackground()` of an AsyncTask. – Swayam Oct 10 '12 at 15:54
0

As the name of the exception indicates, you are not allowed to perform a networking operation on the main thread. See the reference documentation.

Hans
  • 2,448
  • 2
  • 24
  • 30
0

A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. Some examples of other operations that ICS and HoneyComb won't allow you to perform on the UI thread are:

  1. Opening a Socket connection (i.e. new Socket()).
  2. HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
  3. Attempting to connect to a remote MySQL database.
  4. Downloading a file (i.e. Downloader.downloadFile()).

If you are attempting to perform any of these operations on the UI thread, you must wrap them in a worker thread. The easiest way to do this is to use of an AsyncTask, which allows you to perform asynchronous work on your user interface. An AsyncTask will perform the blocking operations in a worker thread and will publish the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

K_Anas
  • 31,226
  • 9
  • 68
  • 81