androidnetwork-programmingnetworkonmainthreadthread-exceptions

Network On Main Thread Exception 1156


Trying to connect my android app to MySQL on my wamp server and i get the following exception when i run the app on my phone...

11-11 18:13:47.732: E/AndroidRuntime(15120): FATAL EXCEPTION: main
11-11 18:13:47.732: E/AndroidRuntime(15120): Process: com.example.loginactivity, PID: 15120
11-11 18:13:47.732: E/AndroidRuntime(15120): android.os.NetworkOnMainThreadException
11-11 18:13:47.732: E/AndroidRuntime(15120):    at    android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1156)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at libcore.io.IoBridge.connect(IoBridge.java:112)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:460)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at java.net.Socket.connect(Socket.java:833)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at library.JSONParser.getJSONFromUrl(JSONParser.java:42)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at library.UserFunctions.registerUser(UserFunctions.java:61)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at com.example.loginactivity.RegisterActivity$1.onClick(RegisterActivity.java:57)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at android.view.View.performClick(View.java:4633)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at android.view.View$PerformClick.run(View.java:19330)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at android.os.Handler.handleCallback(Handler.java:733)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at android.os.Handler.dispatchMessage(Handler.java:95)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at android.os.Looper.loop(Looper.java:157)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at android.app.ActivityThread.main(ActivityThread.java:5356)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at java.lang.reflect.Method.invokeNative(Native Method)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at java.lang.reflect.Method.invoke(Method.java:515)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
11-11 18:13:47.732: E/AndroidRuntime(15120):    at dalvik.system.NativeStart.main(Native Method)

This is the code from the class where the exception is thrown..

    public class RegisterActivity extends Activity {
    Button btnRegister;
    Button btnLinkToLogin;
    EditText inputFullName;
    EditText inputEmail;
    EditText inputPassword;
    TextView registerErrorMsg;

    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";
    private static String KEY_ERROR_MSG = "error_msg";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);          

        // Importing all assets like buttons, text fields
        inputFullName = (EditText) findViewById(R.id.registerName);
        inputEmail = (EditText) findViewById(R.id.registerEmail);
        inputPassword = (EditText) findViewById(R.id.registerPassword);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
        registerErrorMsg = (TextView) findViewById(R.id.register_error);

        // Register Button Click event
        btnRegister.setOnClickListener(new View.OnClickListener() {         
            public void onClick(View view) {
                String name = inputFullName.getText().toString();
                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.registerUser(name, email, password);

                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        registerErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS); 
                        if(Integer.parseInt(res) == 1){
                            // user successfully registred
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user");

                            // Clear all previous data in database
                            userFunction.logoutUser(getApplicationContext());
                            db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        
                            // Launch Dashboard Screen
                            Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
                            // Close all views before launching Dashboard
                            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(dashboard);
                            // Close Registration Screen
                            finish();
                        }else{
                            // Error in registration
                            registerErrorMsg.setText("Error occured in registration");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        // Link to Login Screen
        btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        LoginActivity.class);
                startActivity(i);
                // Close Registration View
                finish();
            }
        });
    }
}

Any help on this be greatly appreciated :)


Solution

  • As jimmy0251 correctly mentioned.... Android prevents you from setting up a network connection on the main thread... You need to outsource it to a seperate thread.. See http://developer.android.com/reference/android/os/AsyncTask.html for further informations