0
votes

Hello I am trying to create a app that send out a variable to server but it keep dying when I try to send the response to a server

here is the code

 package com.example.door;

  import java.io.IOException;
  import java.io.UnsupportedEncodingException;
  import java.util.ArrayList; 
  import java.util.List;
  import org.apache.http.NameValuePair;
  import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.HttpClient; 
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
    Button opendoor;
    Button closedoor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Make Object for Buttons
        //  sendButton = (Button) findViewById(R.id.sendButton);
            Button openbutton = (Button) findViewById(R.id.openButton);
        Button  closebutton = (Button) findViewById(R.id.closeButton);

    }
    //When the send button is clicked
    public void open(View v)
    {
        String server ="http://devel.foo.bar/04r0450240";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost =new HttpPost(server);
        try{
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("led", "1"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            try {
                httpclient.execute(httppost);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
         } catch (IOException e) {
             // TODO Auto-generated catch block
             Log.i("HTTP Failed", e.toString());
         }            

         return;
     }



    public void close(View v){

     HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://devel.foo.bar/04r0450240");

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
               nameValuePairs.add(new BasicNameValuePair("led", "0"));
               httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
               httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Error 11-01 03:55:04.622: E/AndroidRuntime(1612): FATAL EXCEPTION: main 11-01 03:55:04.622: E/AndroidRuntime(1612): java.lang.IllegalStateException: Could not execute method of the activity 11-01 03:55:04.622: E/AndroidRuntime(1612): at android.view.View$1.onClick(View.java:3633) 11-01 03:55:04.622: E/AndroidRuntime(1612): at android.view.View.performClick(View.java:4240) 11-01 03:55:04.622: E/AndroidRuntime(1612): at android.view.View$PerformClick.run(View.java:17721) 11-01 03:55:04.622: E/AndroidRuntime(1612): at android.os.Handler.handleCallback(Handler.java:730) 11-01 03:55:04.622: E/AndroidRuntime(1612): at android.os.Handler.dispatchMessage(Handler.java:92) 11-01 03:55:04.622: E/AndroidRuntime(1612): at android.os.Looper.loop(Looper.java:137) 11-01 03:55:04.622: E/AndroidRuntime(1612): at android.app.ActivityThread.main(ActivityThread.java:5103) 11-01 03:55:04.622: E/AndroidRuntime(1612): at java.lang.reflect.Method.invokeNative(Native Method) 11-01 03:55:04.622: E/AndroidRuntime(1612): at java.lang.reflect.Method.invoke(Method.java:525) 11-01 03:55:04.622: E/AndroidRuntime(1612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 11-01 03:55:04.622: E/AndroidRuntime(1612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 11-01 03:55:04.622: E/AndroidRuntime(1612): at dalvik.system.NativeStart.main(Native Method) 11-01 03:55:04.622: E/AndroidRuntime(1612): Caused by: java.lang.reflect.InvocationTargetException 11-01 03:55:04.622: E/AndroidRuntime(1612): at java.lang.reflect.Method.invokeNative(Native Method) 11-01 03:55:04.622: E/AndroidRuntime(1612): at java.lang.reflect.Method.invoke(Method.java:525) 11-01 03:55:04.622: E/AndroidRuntime(1612): at android.view.View$1.onClick(View.java:3628) 11-01 03:55:04.622: E/AndroidRuntime(1612): ... 11 more 11-01 03:55:04.622: E/AndroidRuntime(1612): Caused by: android.os.NetworkOnMainThreadException 11-01 03:55:04.622: E/AndroidRuntime(1612): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133) 11-01 03:55:04.622: E/AndroidRuntime(1612): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 11-01 03:55:04.622: E/AndroidRuntime(1612): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 11-01 03:55:04.622: E/AndroidRuntime(1612): at java.net.InetAddress.getAllByName(InetAddress.java:214) 11-01 03:55:04.622: E/AndroidRuntime(1612): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 11-01 03:55:04.622: E/AndroidRuntime(1612): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 11-01 03:55:04.622: E/AndroidRuntime(1612): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 11-01 03:55:04.622: E/AndroidRuntime(1612): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 11-01 03:55:04.622: E/AndroidRuntime(1612): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 11-01 03:55:04.622: E/AndroidRuntime(1612): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 11-01 03:55:04.622: E/AndroidRuntime(1612): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 11-01 03:55:04.622: E/AndroidRuntime(1612): at com.example.door.MainActivity.open(MainActivity.java:51) 11-01 03:55:04.622: E/AndroidRuntime(1612): ... 14 more 11-01 03:55:09.212: I/Process(1612): Sending signal. PID: 1612 SIG: 9

Thanks in advance Jeff

3
Working with the internet in the main thread - is prohibited.Siruk Viktor

3 Answers

1
votes

You are trying to start a network connection from UI thread of your application which is not allowed by Android SDK.

You can subclass AsyncTask class provided in the Android SDK to separate out the network calls to separate threads.

Here is the link http://developer.android.com/reference/android/os/AsyncTask.html

Hope it helps.

0
votes

try adding this in your onCreate() method

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

You will need to move the method you of the request into an background thread. I recommend to use AsyncTask. You can do it like this:

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    Button opendoor;
    Button closedoor;

    private static final int CLOSE_METHOD = 1;
    private static final int OPEN_METHOD = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Make Object for Buttons
        // sendButton = (Button) findViewById(R.id.sendButton);
        Button openbutton = (Button) findViewById(R.id.openButton);
        Button closebutton = (Button) findViewById(R.id.closeButton);

    }

    // When the send button is clicked
    public void open(View v) {
        BackgroundTask openTask = new BackgroundTask();
        openTask.execute(OPEN_METHOD);
        return;
    }

    public void close(View v) {
        BackgroundTask closeTask = new BackgroundTask();
        closeTask.execute(CLOSE_METHOD);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    class BackgroundTask extends AsyncTask<Integer, Void, String> {

        @Override
        protected String doInBackground(Integer... params) {
            switch (params[0]) {
            case CLOSE_METHOD:
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://devel.foo.bar/04r0450240");
                try {
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                            1);
                    nameValuePairs.add(new BasicNameValuePair("led", "0"));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    httpclient.execute(httppost);
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case OPEN_METHOD:
                String server = "http://devel.foo.bar/04r0450240";
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(server);
                try {
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                            1);
                    nameValuePairs.add(new BasicNameValuePair("led", "1"));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    try {
                        httpclient.execute(httppost);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Log.i("HTTP Failed", e.toString());
                }
                break;
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // Here you can do something after the Asynctask has finished.
            super.onPostExecute(result);
        }

    }

}

The idea is that Android doesn't let you do Network operations on the Main thread. AsyncTask is the best solution in your case ... it also has onPreExecute() method that is called before the doInBackground starts, here you can do some initialization for the process, or you can display an loading window and dismiss it in onPostExecute() method.

Hope this helps you.