title: On back pressed goes to login screen after register
body: <p>I made an app that requires the user to register. The first time user opens the app - login screen opens. They need to click on the "go to register" button to go to register activity. After they register, they are automatically logged in. </p>
  
  <p>Now here is the issue - when the user first registers he is sent to MainActivity. He should press back and the app should close. But when he tries to exit the app he presses the back button and instead of app closing it goes back to login screen.
  The next time I try to sign in, I have no problem - it goes straight to the MainActivity.</p>
  
  <p>This is how my activities look like:</p>
  
  <p>LoginActivity:</p>
  
  <pre><code>public class LoginActivity extends AppCompatActivity {
  private static final String TAG = "LoginActivity";
  private static final int REQUEST_REGISTER = 0;
  
  @InjectView(R.id.input_email) EditText _emailText;
  @InjectView(R.id.input_password) EditText _passwordText;
  @InjectView(R.id.btn_login) Button _loginButton;
  @InjectView(R.id.link_register) TextView _registerLink;
  
  CheckBox checkBoxShowPassword;
  
  private SessionManager session;
  private SQLiteHandler db;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_login);
      ButterKnife.inject(this);
  
      // SQLite database handler
      db = new SQLiteHandler(getApplicationContext());
      // Session manager
      session = new SessionManager(getApplicationContext());
      // Check if user is already logged in or not
      if (session.isLoggedIn()) {
          // User is already logged in. Take him to main activity
          Intent intent = new Intent(LoginActivity.this, MainActivity.class);
          startActivity(intent);
          finish();
      }
  
      _loginButton.setOnClickListener(new View.OnClickListener() {
  
          @Override
          public void onClick(View v) {
              String email = _emailText.getText().toString().trim();
              String password = _passwordText.getText().toString().trim();
  
              if (!email.isEmpty() &amp;&amp; !password.isEmpty()) {
                  // login user
                  login(email, password);
              } else {
                  // Prompt user to enter credentials
                  Toast.makeText(getApplicationContext(),
                          "Please enter the credentials!", Toast.LENGTH_LONG)
                          .show();
              }
          }
      });
  
      //        Go to register screen
      _registerLink.setOnClickListener(new View.OnClickListener() {
  
          @Override
          public void onClick(View v) {
              // Start the Register activity
              Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
              startActivityForResult(intent, REQUEST_REGISTER);
          }
      });
  
      //        Password checkbox
      checkBoxShowPassword = (CheckBox) findViewById(R.id.checkBoxShowPassword);
      checkBoxShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
  
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              // checkbox status is changed from uncheck to checked.
              if (!isChecked) {
                  // show password
                  _passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
              } else {
                  // hide password
                  _passwordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
              }
          }
      });
  }
  
  //    Login
  public void login(final String email, final String password) {
      Log.d(TAG, "Login");
  
      if (!validate()) {
          onLoginFailed();
          return;
      }
  
      //        Change to false for disabling after error
      _loginButton.setEnabled(true);
  
      String tag_string_req = "req_login";
  
      final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
              R.style.AppTheme_Dark_Dialog);
      progressDialog.setIndeterminate(true);
      progressDialog.setMessage("Authenticating...");
      progressDialog.show();
  
      // TODO: Implementing authentication logic
  
      StringRequest strReq = new StringRequest(Request.Method.POST,
              AppConfig.URL_LOGIN, new Response.Listener&lt;String&gt;() {
  
          @Override
          public void onResponse(String response) {
              Log.d(TAG, "Login Response: " + response.toString());
              progressDialog.dismiss();
  
              try {
                  JSONObject jObj = new JSONObject(response);
                  boolean error = jObj.getBoolean("error");
  
                  // Check for error node in json
                  if (!error) {
                      // user successfully logged in
                      // Create login session
                      session.setLogin(true);
  
                      // Now store the user in SQLite
                      String uid = jObj.getString("uid");
  
                      JSONObject user = jObj.getJSONObject("user");
                      String name = user.getString("name");
                      String email = user.getString("email");
                      String created_at = user
                              .getString("created_at");
  
                      // Inserting row in users table
                      db.addUser(name, email, uid, created_at);
  
                      // Launch main activity
                      Intent intent = new Intent(LoginActivity.this,
                              MainActivity.class);
                      startActivity(intent);
                      finish();
                  } else {
                      // Error in login. Get the error message
                      String errorMsg = jObj.getString("error_msg");
                      Toast.makeText(getApplicationContext(),
                              errorMsg, Toast.LENGTH_LONG).show();
                  }
              } catch (JSONException e) {
                  // JSON error
                  e.printStackTrace();
                  Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
              }
  
          }
      }, new Response.ErrorListener() {
  
          @Override
          public void onErrorResponse(VolleyError error) {
              Log.e(TAG, "Login Error: " + error.getMessage());
  
              Toast toast = Toast.makeText(getApplicationContext(),
                      "Registration failed due to connectivity issues", Toast.LENGTH_LONG);
              toast.setGravity(Gravity.CENTER, 0, 0);
              toast.show();
      //                _loginButton.setEnabled(true);
              progressDialog.dismiss();
  
          }
      }) {
  
          @Override
          protected Map&lt;String, String&gt; getParams() {
              // Posting parameters to login url
              Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();
              params.put("email", email);
              params.put("password", password);
  
              return params;
          }
  
      };
  
      // Adding request to request queue
      AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
  
  
  @Override
  public void onBackPressed() {
      // disable going back to the MainActivity
      moveTaskToBack(true);
  }
  
  public void onLoginSuccess() {
      _loginButton.setEnabled(true);
      finish();
  }
  
  public void onLoginFailed() {
      Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
  
      _loginButton.setEnabled(true);
  }
  
  //    Validation
  public boolean validate() {
      boolean valid = true;
  
      String email = _emailText.getText().toString();
      String password = _passwordText.getText().toString();
  
      if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
          _emailText.setError("Enter a valid email address");
          valid = false;
      } else {
          _emailText.setError(null);
      }
  
      if (password.isEmpty() || password.length() &lt; 4 || password.length() &gt; 20) {
          _passwordText.setError("Enter between 4 and 20 alphanumeric characters");
          valid = false;
      } else {
          _passwordText.setError(null);
      }
  
      return valid;
  }
  }
  </code></pre>
  
  <p>RegisterActivity</p>
  
  <pre><code>public class RegisterActivity extends AppCompatActivity {
  private static final String TAG = "RegisterActivity";
  
  @InjectView(R.id.input_name) EditText _nameText;
  @InjectView(R.id.input_email) EditText _emailText;
  @InjectView(R.id.input_password) EditText _passwordText;
  @InjectView(R.id.btn_register) Button _registerButton;
  @InjectView(R.id.link_login) TextView _loginLink;
  
  CheckBox checkBoxShowPassword;
  
  private SessionManager session;
  private SQLiteHandler db;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_register);
      ButterKnife.inject(this);
  
      // Session manager
      session = new SessionManager(getApplicationContext());
      // SQLite database handler
      db = new SQLiteHandler(getApplicationContext());
      // Check if user is already logged in or not
      if (session.isLoggedIn()) {
          // User is already logged in. Take him to main activity
          Intent intent = new Intent(RegisterActivity.this,
                  MainActivity.class);
          startActivity(intent);
          finish();
      }
  
      //        Register button
      _registerButton.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              String name = _nameText.getText().toString().trim();
              String email = _emailText.getText().toString().trim();
              String password = _passwordText.getText().toString().trim();
              String phone = getMyPhoneNumber();
  
              if (!name.isEmpty() &amp;&amp; !email.isEmpty() &amp;&amp; !password.isEmpty()) {
                  register(name, email, password, phone);
              } else {
                  Toast.makeText(getApplicationContext(),
                          "Please enter your details!", Toast.LENGTH_LONG)
                          .show();
              }
          }
      });
  
      //        Go to login screen
      _loginLink.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              // Finish the registration screen and return to the Login activity
              finish();
          }
      });
  
      //        Password checkbox
      checkBoxShowPassword = (CheckBox) findViewById(R.id.checkBoxShowPassword);
      checkBoxShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
  
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              // checkbox status is changed from uncheck to checked.
              if (!isChecked) {
                  // show password
                  _passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
              } else {
                  // hide password
                  _passwordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
              }
          }
      });
  }
  
     //    Register
  public void register(final String name, final String email, final String password, final String phone) {
      Log.d(TAG, "Register");
  
      if (!validate()) {
          onRegisterFailed();
          return;
      }
  
      _registerButton.setEnabled(false);
  
      String tag_string_req = "req_register";
  
      final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this,
              R.style.AppTheme_Dark_Dialog);
      progressDialog.setIndeterminate(true);
      progressDialog.setMessage("Creating Account...");
      progressDialog.show();
  
      // TODO: Implementing register logic
      StringRequest strReq = new StringRequest(Request.Method.POST,
              AppConfig.URL_REGISTER, new Response.Listener&lt;String&gt;() {
  
          @Override
          public void onResponse(String response) {
              Log.d(TAG, "Register Response: " + response.toString());
              progressDialog.dismiss();
  
              try {
                  JSONObject jObj = new JSONObject(response);
                  boolean error = jObj.getBoolean("error");
                  if (!error) {
                      // User successfully stored in MySQL
                      // Now store the user in sqlite
                      String uid = jObj.getString("uid");
  
                      JSONObject user = jObj.getJSONObject("user");
                      String name = user.getString("name");
                      String email = user.getString("email");
                      String created_at = user
                              .getString("created_at");
  
                      // Inserting row in users table
                      db.addUser(name, email, uid, created_at);
  
                      //TODO: insert contacts to local db
                      String[] PROJECTION = new String[] {
                              ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                              ContactsContract.CommonDataKinds.Phone.NUMBER
                      };
  
                      Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
                      while (phones.moveToNext()) {
                          if (phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER) != -1)
                          {
                              String username = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                              String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
  
                              db.addContact(username, phoneNumber);
                          }
                      }
                      phones.close();
  
                      Toast.makeText(getApplicationContext(), "Registration successful!", Toast.LENGTH_LONG).show();
  
       //                        Auto login
                      session.setLogin(true);
  
                      // Launch login activity
                      Intent intent = new Intent(
                              RegisterActivity.this,
                              MainActivity.class);
                      startActivity(intent);
                      finish();
                  } else {
  
                      // Error occurred in registration. Get the error
                      // message
                      String errorMsg = jObj.getString("error_msg");
                      Toast.makeText(getApplicationContext(),
                              errorMsg, Toast.LENGTH_LONG).show();
                  }
              } catch (JSONException e) {
                  e.printStackTrace();
              }
  
          }
      }, new Response.ErrorListener() {
  
          @Override
          public void onErrorResponse(VolleyError error) {
              Log.e(TAG, "Registration Error: " + error.getMessage());
              Toast toast = Toast.makeText(getApplicationContext(),
                      "Registration failed due to connectivity issues", Toast.LENGTH_LONG);
              toast.setGravity(Gravity.CENTER, 0, 0);
              toast.show();
              _registerButton.setEnabled(true);
              progressDialog.dismiss();
          }
      }) {
  
          @Override
          protected Map&lt;String, String&gt; getParams() {
              // Posting params to register url
              Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();
              params.put("name", name);
              params.put("email", email);
              params.put("password", password);
              params.put("phone", phone);
  
              return params;
          }
  
      };
  
      // Adding request to request queue
      AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
  
  }
  
  public void onRegisterSuccess() {
      _registerButton.setEnabled(true);
      setResult(RESULT_OK, null);
      finish();
  }
  
  public void onRegisterFailed() {
      Toast.makeText(getBaseContext(), "Registration failed", Toast.LENGTH_LONG).show();
  
      _registerButton.setEnabled(true);
  }
  
      //    Validation
  public boolean validate() {
      boolean valid = true;
  
      String name = _nameText.getText().toString();
      String email = _emailText.getText().toString();
      String password = _passwordText.getText().toString();
  
      if (name.isEmpty() || name.length() &lt; 3) {
          _nameText.setError("Enter at least 3 characters");
          valid = false;
      } else {
          _nameText.setError(null);
      }
  
      if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
          _emailText.setError("Enter a valid email address");
          valid = false;
      } else {
          _emailText.setError(null);
      }
  
      if (password.isEmpty() || password.length() &lt; 4 || password.length() &gt; 20) {
          _passwordText.setError("Enter between 4 and 20 alphanumeric characters");
          valid = false;
      } else {
          _passwordText.setError(null);
      }
  
      return valid;
  }
  
  // Get users phone number
  private String getMyPhoneNumber() {
      TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
      String MyPhoneNumber = "0000000000";
  
      try
      {
          MyPhoneNumber =tMgr.getLine1Number();
      }
      catch(NullPointerException ex)
      {
      }
  
      if(MyPhoneNumber.equals("")){
          MyPhoneNumber = tMgr.getSubscriberId();
      }
  
      return MyPhoneNumber;
  }
  
  private String getMy10DigitPhoneNumber() {
      String s = getMyPhoneNumber();
      return s.substring(2);
  }
  }
  </code></pre>