0

When I use my android phone to sent json to the server and the application is creashed. But it works when I use emulator.

Application has stopped unexpectedly!

Code:

String url = <<the url>>;
DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost(url);


List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));

try {
  httpPost.setEntity(new UrlEncodedFormEntity(params));
                          httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
                    } catch (UnsupportedEncodingException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    HttpResponse httpResponse = null;
                    StringBuilder builder = new StringBuilder();
                    JSONTokener tokener = null;
                    try {
                        httpResponse = httpClient.execute(httpPost);
                        HttpEntity entity = httpResponse.getEntity();

                        InputStream content = entity.getContent();

                        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
    String line;

    while((line = reader.readLine()) != null){
    builder.append(line);
    }
    tokener = new JSONTokener(builder.toString());
    String execution = null;

    try{
    //convert the api response into json object
    JSONObject jsonObject = new JSONObject(tokener);
    execution = jsonObject.get("execution").toString();

    //display the json object
    } catch(Exception e){
    e.printStackTrace();
    }

    if (execution.equals("true")){
    //run method to open message dialog
    openSuccessDialog(v, "You have logged in your account.");
    }
    else{
    //run method to open message dialog
    openErrorDialog(v, "Execution false. Your email and password doesn't match.");
                        }

LogCat:

08-01 10:26:52.985: W/dalvikvm(4335): threadid=1: thread exiting with uncaught exception (group=0x416a7e18)
08-01 10:26:52.995: E/AndroidRuntime(4335): FATAL EXCEPTION: main
08-01 10:26:52.995: E/AndroidRuntime(4335): Process: com.entityaccess.assetmappingsprintone, PID: 4335
08-01 10:26:52.995: E/AndroidRuntime(4335): android.os.NetworkOnMainThreadException
08-01 10:26:52.995: E/AndroidRuntime(4335):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1239)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at libcore.io.IoBridge.connect(IoBridge.java:112)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at java.net.Socket.connect(Socket.java:873)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:125)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:367)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:519)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:497)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at com.entityaccess.assetmappingsprintone.LoginActivity$1.onClick(LoginActivity.java:119)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at android.view.View.performClick(View.java:4480)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at android.view.View$PerformClick.run(View.java:18686)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at android.os.Handler.handleCallback(Handler.java:733)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at android.os.Handler.dispatchMessage(Handler.java:95)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at android.os.Looper.loop(Looper.java:157)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at android.app.ActivityThread.main(ActivityThread.java:5872)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at java.lang.reflect.Method.invokeNative(Native Method)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at java.lang.reflect.Method.invoke(Method.java:515)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
08-01 10:26:52.995: E/AndroidRuntime(4335):     at dalvik.system.NativeStart.main(Native Method)
08-01 10:26:55.858: D/Process(4335): killProcess, pid=4335
08-01 10:26:55.858: D/Process(4335): com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:131 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690 

How can I solve this to make my phone be able to send json to the server?

  • THis is one of the most frequently asked Android question. I've closed 3 of them today. Please do some research before asking a question. – Gabe Sechan Aug 01 '14 at 02:44

3 Answers3

0

You cannot make network calls on the main thread. You need to run this code in a separate thread and your problem will be solved.

The exception is quite explanatory!

08-01 10:26:52.995: E/AndroidRuntime(4335): android.os.NetworkOnMainThreadException

You have many choices to choose from on Android. You could use the well know Thread class from java. Or you could use AsyncTask. You could also throw this into an IntentService if you wanted. The options are there, it's up to you to choose the best option for your needs.

Miguel
  • 19,793
  • 8
  • 56
  • 46
0

Well first of all this question has been asked numerous times...You should probably do some searching before asking the question :)

The error basically means that you are running an http request on UI thread, which is something you are not supposed to do. What you want to do instead is put the request in an Asynctask like so:

class postRequest extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String url = <<the url>>;
DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost(url);


List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));

try {
  httpPost.setEntity(new UrlEncodedFormEntity(params));
                          httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
                    } catch (UnsupportedEncodingException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    HttpResponse httpResponse = null;
                    StringBuilder builder = new StringBuilder();
                    JSONTokener tokener = null;
                    try {
                        httpResponse = httpClient.execute(httpPost);
                        HttpEntity entity = httpResponse.getEntity();

                        InputStream content = entity.getContent();

                        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
    String line;

    while((line = reader.readLine()) != null){
    builder.append(line);
    }
    tokener = new JSONTokener(builder.toString());
    String execution = null;

    try{
    //convert the api response into json object
    JSONObject jsonObject = new JSONObject(tokener);
    execution = jsonObject.get("execution").toString();

    //display the json object
    } catch(Exception e){
    e.printStackTrace();
    }

    if (execution.equals("true")){
    //run method to open message dialog
    openSuccessDialog(v, "You have logged in your account.");
    }
    else{
    //run method to open message dialog
    openErrorDialog(v, "Execution false. Your email and password doesn't match.");
                        }


 }
StephenChen
  • 711
  • 2
  • 8
  • 20
0

Create an AsyncTask and put your code inside doInBackground.

private class YourTask extends AsyncTask<String, String, String> {
     protected Long doInBackground(String... params) {
         // your network call here
     }

     protected void onPostExecute(String result) {
         // open your dialogs here
     }
 }

Then call execute to run your task:

new YourTask().execute();

Explanation: In Android, all network access (and any other blocking code) need to be done outside the main thread so that the UI doesn't block. AsyncTask is a convenient way of doing that. It runs doInBackground in a new thread and, when it's done, it runs onPostExecute back in the main thread, so you can show the results in the UI.

Victor Basso
  • 5,556
  • 5
  • 42
  • 60