0

We are making an Android app that has a login function and mySQL database stored on the server. I found a piece of code and got it to work fine on Android device lower than API level 3.0. Anything beyond that will crash. I was told to use Asynctask to solve my issue. To seperate UI code from the network code? Was told it should be easy but I have no idea how to get it to work. Can anyone should me exactly what I need to do to make this code work? I have spent countless of hours researching into this problem and still no luck. I appreciate any help. Thank you

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();
        }
    });
}
}

Here is also the logCatError

 D/AndroidRuntime(10040): Shutting down VM
 W/dalvikvm(10040): threadid=1: thread exiting with uncaught exception (group=0x416f2930)
 E/AndroidRuntime(10040): FATAL EXCEPTION: main
 E/AndroidRuntime(10040): android.os.NetworkOnMainThreadException
 E/AndroidRuntime(10040):    at     android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
 E/AndroidRuntime(10040):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
 E/AndroidRuntime(10040):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
 E/AndroidRuntime(10040):    at libcore.io.IoBridge.connect(IoBridge.java:112)
 E/AndroidRuntime(10040):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
 E/AndroidRuntime(10040):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
 E/AndroidRuntime(10040):    at java.net.Socket.connect(Socket.java:842)
Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78
E. X
  • 87
  • 1
  • 10

2 Answers2

1

From the ICS and above versions Android won't allowed any network operation in the UI thread.It should be done in separate thread so it won't hang the UI.Try your network communication code in the separate thread.

Refer this Link.It explains why this occurs on Android 3.0 and above.

AndroidLearner
  • 4,500
  • 4
  • 31
  • 62
0

It is true that android has become very strict about UI thread and wont allow you to perform background calculations on UI thread as it decrease the performance.You were told right to use async task for performing network communications. You can do it by executing asyncTask at onCLick of your register button using new yourTask().execute();.

Then write an asyncTask class like this

private class yourTask extends AsyncTask<Integer, Void, Integer> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //show a progress bar 
    }

    @Override
    protected String doInBackground(Integer... params) {
       // your network communication code will be here.
        return 0; 
    }      

    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
       //show the result here
    }
}
Vikram Singh
  • 1,420
  • 14
  • 19