0

I am getting android.os.NetworkOnMainThreadException in my Login Activity. Basically I am simply trying to check if the user id and password entered by the user are correct i.e., is the user allowed to sign in or not. I have searched for a solution and know that the exception has got something to do with networking on main thread. But I am using AsyncTask. I am still getting this exception. Here is my LoginActivity.java

    public class LoginActivity extends AppCompatActivity {

    JSONParser jsonParser = new JSONParser();
    // single product url
    private static final String url_user_check_login = "##########################/android_connect/db_connect.php";
     int success=0;
    String id="";
    String password="";
    private static final String TAG_SUCCESS = "success";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

//        Defining onClickListener for Login Button
        Button loginBtn=(Button) findViewById(R.id.login_btn);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Check credentials
                EditText phone=(EditText)findViewById(R.id.phone_txt);
                EditText pwd=(EditText)findViewById(R.id.password_txt);
                id=phone.getText().toString();
                password=pwd.getText().toString();
                new CheckUserLogin().execute();
                if (success == 1) {

                    Intent intent=new Intent(getApplicationContext(), RideDetailsActivity.class);
                    startActivity(intent);

                }else{
                    // product with id not found
                }
            }
        });
    }
    class CheckUserLogin extends AsyncTask<String, String, String> {

        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag

                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("id", id));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                url_user_check_login, "GET", params);

                        // check your log for json response
//                        Log.d("Single Product Details", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }


    }
}

I don't know if this is important but I tried debugging and put break points inside the doInBackground method but my debugger just ignores the break points and it just blows past the new CheckUserLogin().execute(); statement.

Also here is my exception stack trace.

    FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:587)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:511)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:489)
at com.heycabs.heycabs.JSONParser.makeHttpRequest(JSONParser.java:65)
at com.heycabs.heycabs.LoginActivity$CheckUserLogin$1.run(LoginActivity.java:98)at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5409)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
at dalvik.system.NativeStart.main(Native Method)
Rehan Yousaf
  • 235
  • 2
  • 4
  • 13
  • 1
    You are completely defeating the purpose of using an `AsyncTask` by running everything there on the UI thread with `runOnUiThread()`. That's also why you're getting the `NetworkOnMainThreadException`. – Mike M. Jul 21 '16 at 18:44
  • Thanks for pointing that out. I am new to android and I am using [this](http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/) tutorial as a guide. Can you let me know what i should change? – Rehan Yousaf Jul 21 '16 at 18:47

1 Answers1

0

You are incorrectly using Asynktask. success == 1 will never excute, since synchronous commands would happen in nanoseconds, and network, would take several milliseconds.

Do startActivity(intent) on the Asynk completion.... finally you created a new Thread, and in it, went back to the UI one:

runOnUiThread(new Runnable()

This is incorrect. Please read documentation on AsynkTask. And read this example

Community
  • 1
  • 1
Bonatti
  • 2,778
  • 5
  • 23
  • 42
  • Thanks for pointing that out. I am new to android and I am using [this](http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/) tutorial as a guide. Can you let me know what i should change? – Rehan Yousaf Jul 21 '16 at 18:48
  • From the tutorial you linked, check the `doInBackground` and `onPostExecute` functions from AsynkTask. Those functions are "the before" and "the after" functions used. I also highly suggest you google Volley. Its a network related library, that facilitate LOTS of network operations, and is very easy to use. – Bonatti Jul 25 '16 at 14:22