Search code examples
androidmultithreadingandroid-asynctaskandroid-runonuithread

Exception android.os.NetworkOnMainThreadException


When I try to run this code it gives my this error android.os.NetworkOnMainThreadException Here is the complete code:

final EditText editText = (EditText) findViewById(R.id.ed);
    Button buttonX = (Button) findViewById(R.id.ok);
    buttonX.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String message = editText.getText().toString();
            new Thread() {
                public void run() {
                    Log_in.this.runOnUiThread(new Runnable() {
                        @Override 
                        public void run() {
                            try {
                                URL url = new URL(message);
                                HttpURLConnection.setFollowRedirects(false);
                                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                                con.setRequestMethod("HEAD");
                                con.connect();
                                Log.d("URL Result", "con.getResponseCode() IS : " + con.getResponseCode());
                                if ((con.getResponseCode() >= 200) && (con.getResponseCode() <= 399)) {
                                    Log.d("URL Result", "Sucess");

                                    Toast.makeText(getBaseContext(), "GOOD!", Toast.LENGTH_SHORT).show();

                                    Intent intent = new Intent(Log_in.this, MainActivity.class);
                                    startActivity(intent);
                                } else
                                    Log.d("URL Result", "con.getResponseCode() IS : " + con.getResponseCode());
                            } catch (Exception e)

                            {
                                e.printStackTrace();
                                Log.d("URL Result", "fail");
                            }
                        }
                    });
                }
            }.start();
        }
    });
}

I think I should use AsyncTask but I do not know how to use it on my current code, does someone have any idea how I should do this or my code is messed up and I should change it somehow?


Solution

  • new Thread() {
           public void run() {
                 Log_in.this.runOnUiThread(new Runnable() {
    

    you are spawning a thread just to make its run method run on the UI Thread. That's the reason why you are getting the NetworkOnMainThreadException. You have to use

     Log_in.this.runOnUiThread(new Runnable() {
    

    only to make changes to the UI and to show your Toast