0

This is my code to request to server..

    final SyncHttpClient client = new SyncHttpClient();

    RequestParams params = new RequestParams();
    params.put("product[name]", name);
    params.put("product[price]", price);

    client.post(context,Config.URL_GET_ALL_PRODUCT, params, new AsyncHttpResponseHandler() {
        @Override
        public void onStart() {

            super.onStart();
            setUseSynchronousMode(true);
        }
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            try {
                JSONObject eventResult = new JSONObject(result);

                String id = eventResult.getString("id");
                // Check for error node in json
                if (id != null || id != "" ) {
                    Toast.makeText(context,
                            "New Product Added", Toast.LENGTH_LONG).show();
                } else {
                    // Error in login. Get the error message
                    String errorMsg = eventResult.getString("error_msg");
                    Toast.makeText(context,
                            errorMsg, Toast.LENGTH_LONG).show();
                }


            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }
        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            System.out.println(error.getMessage());
        }
    });
}

And this is my code to call the method in Fragment

 ProductController.addProduct(getContext().getApplicationContext(), nameProduct, priceProduct);

Error for this code

Unhandled exception origin cause android.os.NetworkOnMainThreadException at com.project.roy.interview.Control.ProductController.addProduct(ProductController.java:102) at com.project.roy.interview.Fragment.FragmentAddProduct$1.onClick(FragmentAddProduct.java:38

roihan
  • 5
  • 1

1 Answers1

0

In the documentation of this library its written:

Processes http requests in synchronous mode, so your caller thread will be blocked on each request

On Android you may not block the main thread, thats where your Exception comes from.

Either use an AsyncTask, or execute this code inside a separate thread.

Piwo
  • 1,347
  • 1
  • 12
  • 19