我制作了一个需要用户注册的应用。用户第一次打开应用程序 - 登录屏幕打开。他们需要点击“转到注册”按钮去注册活动。注册后,他们会自动登录。
现在出现问题 - 当用户首次注册时,他被发送到MainActivity。他应该回来,应用程序应该关闭。但当他试图退出应用程序时,他按下后退按钮而不是应用程序关闭它返回登录屏幕。 下次我尝试登录时,我没有问题 - 它直接进入MainActivity。
这就是我的活动的样子:
LoginActivity:
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() && !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<String>() {
@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<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
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() < 4 || password.length() > 20) {
_passwordText.setError("Enter between 4 and 20 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
}
RegisterActivity
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() && !email.isEmpty() && !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<String>() {
@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<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
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() < 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() < 4 || password.length() > 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);
}
}
答案 0 :(得分:1)
当你写
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivityForResult(intent, REQUEST_REGISTER);
这必须覆盖onActivityResult方法来处理该结果。
在该代码中,您只需编写
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intent);
finish();
我希望这可以帮助你。
答案 1 :(得分:1)
按照我的想法,你只需做一件事,当你从登录活动转到register_activity时,就像这样完成login_activity
// 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);
LoginActivity.this.finish();
}
});
如果您仍面临同样的问题,那么当您首先打开login_activity然后创建该类的变量并将值分配给该变量时
public static LoginActivity mLogin_activity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLogin_activity=LoginActivity.this;
如果该值为null,则在onBackPressed()
中的Main_Activity
方法中检查此值是否为null,然后完成该main_activity,否则也完成该login_activity;像这样:
@Override
public void onBackPressed() {
super.onBackPressed();
if (LoginActivity.mLogin_activity!=null) {
LoginActivity.mLogin_activity.finish();
MainActivity.this.finish();
}else {
MainActivity.this.finish();
}
}
希望我已经回答了你的问题...