0

I got a Fatal EXCEPTION: main.

I believe that my exception is caused by the following code:

    public void onClick(View view) {
        String name = inputName.getText().toString();
        String password = inputPassword.getText().toString();
        UserFunctions userFunction = new UserFunctions();
        Log.d("Button", "Login");
            SONObject json = userFunction.loginUser(name, password);

        // check for login response
        try {
            if (json.getString(KEY_SUCCESS) != null) {
                loginErrorMsg.setText("");
                String res = json.getString(KEY_SUCCESS); 
        ....code body

And here is my Logcat

08-20 18:41:26.490: E/AndroidRuntime(4240): FATAL EXCEPTION: main
08-20 18:41:26.490: E/AndroidRuntime(4240): android.os.NetworkOnMainThreadException
08-20 18:41:26.490: E/AndroidRuntime(4240):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-20 18:41:26.490: E/AndroidRuntime(4240):     at   libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-20 18:41:26.490: E/AndroidRuntime(4240):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)

When I change the code to following, I got no Exception.

Log.d("Button", "Login");
//JSONObject json = userFunction.loginUser(name, password);

try {
        if (json.getString(KEY_SUCCESS) != null) {
        loginErrorMsg.setText("");
        String res = json.getString(KEY_SUCCESS);
code body.....

Any help?
Thanks.

Lcyu
  • 11
  • 1

1 Answers1

1

Since Android 3.0 and higher (I may be wrong), you will get an error for doing this on the main thread because your UI may freeze. It is recommended to handle this in an asyncTask as seen here. http://developer.android.com/reference/android/os/AsyncTask.html

Note: If you are new to Android, please realize that async tasks are super important and should be learned as soon as possible. This is what will give your application a smooth UI. Another reason you may want to use AsyncTask is for anything involving a database in android (sqlite).

EGHDK
  • 17,818
  • 45
  • 129
  • 204