-3

I'm trying to create a connection to a servlet and send a Json File, here is the part of the code where the app crashes:

 findViewById(R.id.main_login_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finalJson=createJfile();
            try {
                HTTPConnection(finalJson);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

The function is the following one:

public void HTTPConnection(String Json) throws IOException{
    URL url;
    url = new URL("http://192.168.0.136:8080/ProgettoProva/AndroidApp");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setRequestProperty("Accept", "text/json");
    OutputStreamWriter writer =new OutputStreamWriter(conn.getOutputStream());
    writer.write(Json);
    writer.close();
    conn.disconnect();

}

In the LogCat, nothing is showed. The app just crashed when it starts the function.

Blo
  • 11,903
  • 5
  • 45
  • 99
Gianfranco
  • 43
  • 1
  • 5
  • 1
    because you trying network communication on main thread use asynchtask for background thread http://developer.android.com/reference/android/os/AsyncTask.html – Pavan Dec 15 '15 at 10:54
  • 1
    Possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – Mike M. Dec 15 '15 at 10:58
  • Use `AsyncTask` for using `HttpURLConnection` – Pankaj Dec 15 '15 at 11:03
  • do not call network thread in MainThread... try to use [`AsyncTask`](http://developer.android.com/reference/android/os/AsyncTask.html) for network call.... – khaleel_jageer Dec 15 '15 at 11:03

1 Answers1

1

You should execute network code in a AsyncTask. Android does not allow Networking in the main Thread.

private class MyAsyncTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        //Do network code here
    }

    @Override
    protected void onPostExecute(String result) {

    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}

Execute with

new LongOperation().execute();
Empty2k12
  • 475
  • 12
  • 34