-1

I'm trying to sent a simple HTTP-Request through Android when I'm pressing a certain button. But every time I do so, my app force closes. Why? I'm new to Android developing by the way.

My code:

 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://www.office.school-blog.de/api/check-login.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("User", "Steffen"));
    nameValuePairs.add(new BasicNameValuePair("Password", "test1234"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

And my log file:

03-16 14:36:47.554: D/AndroidRuntime(449): Shutting down VM
03-16 14:36:47.554: W/dalvikvm(449): threadid=1: thread exiting with uncaught exception (group=0x40014760)
03-16 14:36:47.574: E/AndroidRuntime(449): FATAL EXCEPTION: main
03-16 14:36:47.574: E/AndroidRuntime(449): android.os.NetworkOnMainThreadException
03-16 14:36:47.574: E/AndroidRuntime(449):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
03-16 14:36:47.574: E/AndroidRuntime(449):  at java.net.InetAddress.lookupHostByName(InetAddress.java:477)
03-16 14:36:47.574: E/AndroidRuntime(449):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277)
03-16 14:36:47.574: E/AndroidRuntime(449):  at java.net.InetAddress.getAllByName(InetAddress.java:249)
03-16 14:36:47.574: E/AndroidRuntime(449):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
03-16 14:36:47.574: E/AndroidRuntime(449):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-16 14:36:47.574: E/AndroidRuntime(449):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-16 14:36:47.574: E/AndroidRuntime(449):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-16 14:36:47.574: E/AndroidRuntime(449):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-16 14:36:47.574: E/AndroidRuntime(449):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-16 14:36:47.574: E/AndroidRuntime(449):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-16 14:36:47.574: E/AndroidRuntime(449):  at com.shr.khg.DashboardActivity$1.onClick(DashboardActivity.java:89)
03-16 14:36:47.574: E/AndroidRuntime(449):  at android.view.View.performClick(View.java:3110)
03-16 14:36:47.574: E/AndroidRuntime(449):  at android.view.View$PerformClick.run(View.java:11934)
03-16 14:36:47.574: E/AndroidRuntime(449):  at android.os.Handler.handleCallback(Handler.java:587)
03-16 14:36:47.574: E/AndroidRuntime(449):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-16 14:36:47.574: E/AndroidRuntime(449):  at android.os.Looper.loop(Looper.java:132)
03-16 14:36:47.574: E/AndroidRuntime(449):  at android.app.ActivityThread.main(ActivityThread.java:4123)
03-16 14:36:47.574: E/AndroidRuntime(449):  at java.lang.reflect.Method.invokeNative(Native Method)
03-16 14:36:47.574: E/AndroidRuntime(449):  at java.lang.reflect.Method.invoke(Method.java:491)
03-16 14:36:47.574: E/AndroidRuntime(449):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
03-16 14:36:47.574: E/AndroidRuntime(449):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
03-16 14:36:47.574: E/AndroidRuntime(449):  at dalvik.system.NativeStart.main(Native Method)
03-16 14:36:50.064: I/Process(449): Sending signal. PID: 449 SIG: 9

Does anybody know whats wrong?

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
  • 1
    First of all, in any case, if error occured, you should to read error stack trace. `android.os.NetworkOnMainThreadException` - netwrok on main thread exception... If you don't understand what is this from the exception type, just google it. First link references to developer.android.com. First sentence there is: `The exception that is thrown when an application attempts to perform a networking operation on its main thread.`. So it's very simple to understand yourself mistakes. – Anton-M Mar 16 '13 at 15:35

4 Answers4

2

Use AsyncTask.

Do not do network operations on the main thread: It is not allowed for android version >= 3.0.

Do network operations in doInBackground method.

Read here.

Neil Townsend
  • 6,024
  • 5
  • 35
  • 52
Ajay S
  • 48,003
  • 27
  • 91
  • 111
2

This will solve your problem:

class MyHttpPost extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... params) 
{

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.office.school-blog.de/api/check-login.php");

        try {
         // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("User", "Steffen"));
        nameValuePairs.add(new BasicNameValuePair("Password", "test1234"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
    HttpEntity httpEntity = response.getEntity();
                String result = httpEntity.getContent();


        } catch (ClientProtocolException e) {
         // TODO Auto-generated catch block
        } catch (IOException e) {
         // TODO Auto-generated catch block
        }



return true;
                    }

}

Replace the above code in your public class, because the MyHttpPost class is an inner class, we do not create a separate .java file to it.

To use it:

new MyHttpPost().execute();
Alex
  • 1,639
  • 3
  • 18
  • 33
0

Android doesn't allow blocking tasks such as network access on the UI (or main) thread. This is the thread that all things to do with user interaction run. So, you will need to create (probably) and AsynTask class to run the query and feed the information back. See http://developer.android.com/reference/android/os/AsyncTask.html. An example of an AsyncTask is also given here: http://www.javasrilankansupport.com/2012/11/asynctask-android-example-asynctask-in.html

Neil Townsend
  • 6,024
  • 5
  • 35
  • 52
0

You are trying to perform network operation on UI thread, try to take a separate thread or Async task

Pragnani
  • 20,075
  • 6
  • 49
  • 74
cwhsu
  • 1,493
  • 24
  • 31