the Android app crashes when I try to publish JSON data to a web service

advertisements

Hi everybody i'm trying to Send data from my android app to a web service in a json Object but the application crashs when i click the send button any one can help me to slove my problem ? thx , Below is my main java code :

public  class MainActivity extends Activity  {

private Button send;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   send= (Button)findViewById(R.id.btnSend);
   send.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            JSONObject jsonobj; // declared locally so that it destroys after serving  its purpose
            jsonobj = new JSONObject();
            try {
                // adding some keys
                jsonobj.put("name", "toto");
                jsonobj.put("twitter", "twito");
                jsonobj.put("country", "totoland");
            } catch (JSONException ex) {
                //buildref.setText("Error Occurred while building JSON");
                ex.printStackTrace();
            }
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httppostreq = new HttpPost("bbqhmkcode.appspot.com/jsonservlet");
            StringEntity se = null;
            try {
                se = new StringEntity(jsonobj.toString());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            se.setContentType("application/json;charset=UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
            httppostreq.setEntity(se);
            try {
                HttpResponse httpresponse = httpclient.execute(httppostreq);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
 }
}

this is the LogCat :

    08-08 15:11:51.790: I/Process(24024): Sending signal. PID: 24024 SIG: 9
    08-08 15:12:34.440: W/dalvikvm(24321): threadid=11: thread exiting with uncaught                             exception (group=0x41d3e700)
  08-08 15:12:34.510: E/AndroidRuntime(24321): FATAL EXCEPTION: AsyncTask #1
  08-08 15:12:34.510: E/AndroidRuntime(24321): java.lang.RuntimeException: An error occured while executing doInBackground()
 08-08 15:12:34.510: E/AndroidRuntime(24321):   at android.os.AsyncTask$3.done(AsyncTask.java:299)
 08-08 15:12:34.510: E/AndroidRuntime(24321):   at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
 08-08 15:12:34.510: E/AndroidRuntime(24321):   at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
 08-08 15:12:34.510: E/AndroidRuntime(24321):   at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-08 15:12:34.510: E/AndroidRuntime(24321):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-08 15:12:34.510: E/AndroidRuntime(24321):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-08 15:12:34.510: E/AndroidRuntime(24321):    at java.lang.Thread.run(Thread.java:841)
08-08 15:12:34.510: E/AndroidRuntime(24321): Caused by: java.lang.NullPointerException
08-08 15:12:34.510: E/AndroidRuntime(24321):    at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:518)
08-08 15:12:34.510: E/AndroidRuntime(24321):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)

08-08 15:12:34.510: E/AndroidRuntime(24321): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 08-08 15:12:34.510: E/AndroidRuntime(24321): at com.example.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:72) 08-08 15:12:34.510: E/AndroidRuntime(24321): at com.example.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:1) 08-08 15:12:34.510: E/AndroidRuntime(24321): at android.os.AsyncTask$2.call(AsyncTask.java:287) 08-08 15:12:34.510: E/AndroidRuntime(24321): at java.util.concurrent.FutureTask.run(FutureTask.java:234)


you are sending your data from main UI thread. try to send data using AsyncTask<> like this

public  class MainActivity extends Activity  {

private Button send;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

send= (Button)findViewById(R.id.btnSend);
send.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
     // execute like this way
         new HttpAsyncTask().execute("bbqhmkcode.appspot.com/jsonservlet");

 });
}

  private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

           JSONObject jsonobj; // declared locally so that it destroys after serving  its purpose
               jsonobj = new JSONObject();
               try {
                   // adding some keys
                    jsonobj.put("name", "toto");
                    jsonobj.put("twitter", "twito");
                    jsonobj.put("country", "totoland");
                } catch (JSONException ex) {
                    //buildref.setText("Error Occurred while building JSON");
                    ex.printStackTrace();
                }
                DefaultHttpClient httpclient = new DefaultHttpClient();
                HttpPost httppostreq = new HttpPost();
                StringEntity se = null;
                try {
                    se = new StringEntity(jsonobj.toString());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                se.setContentType("application/json;charset=UTF-8");
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
               httppostreq.setEntity(se);

                    HttpResponse httpresponse = httpclient.execute(httppostreq);
                    InputStream inputStream = httpResponse.getEntity().getContent();
                    if(inputStream != null)
                         result = convertInputStreamToString(inputStream);
                    else
                         result = "Did not work!";

      return result;
    }

   private String convertInputStreamToString(InputStream inputStream) throws IOException {
        // TODO Auto-generated method stub

        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        return result;

    }

}

        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
                //you will get result here in "result"
       }
    }

}

i have edited your code but you may need to corrects its format this is how i am using in my way

    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            return POST(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
       }
    }
    public static String POST(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("name", "jaimin");
        jsonObject.accumulate("country","ind");
        jsonObject.accumulate("twitter", "yoooo");

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

      // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
   // 11. return result
    return result;

  }

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    // TODO Auto-generated method stub

    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

  }
  public boolean isConnected() {
    // TODO Auto-generated method stub
     ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
      NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
      if (networkInfo != null && networkInfo.isConnected())
         return true;
      else
         return false;
 }