[英]App stops working when I pressed the sign up button in Android Studio
[英]Android studio sign up not working
我正在使用android studio為android創建社交網絡。 當我在所有字段中輸入文本並單擊Register
沒有任何反應。 我之前檢查了Android Monitor並打印出我沒有使用Internet權限。 所以我在中添加了它。 現在,我沒有收到任何錯誤,單擊“注冊”后仍然沒有任何反應。 當我單擊注冊時,如果注冊成功,則用戶的信息進入數據庫,然后他們進入登錄屏幕。 有人可以幫我解決這個問題嗎?
Android清單:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
registeractivity.java:
public class RegisterActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPw = (EditText) findViewById(R.id.etPw);
final EditText etEmail = (EditText) findViewById(R.id.etEmail);
final Button bRegister = (Button) findViewById(R.id.bRegister);
final TextView loginLink = (TextView) findViewById(R.id.tvLoginHere);
loginLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent loginIntent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(loginIntent);
}
});
bRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String username = etUsername.getText().toString();
final String pw = etPw.getText().toString();
final String email = etEmail.getText().toString();
if (etUsername.getText().toString().trim().length() <= 0) {
Toast.makeText(RegisterActivity.this, "Username is empty", Toast.LENGTH_SHORT).show();
}
if (etPw.getText().toString().trim().length() <= 0) {
Toast.makeText(RegisterActivity.this, "Password is empty", Toast.LENGTH_SHORT).show();
}
if (etEmail.getText().toString().trim().length() <= 0) {
Toast.makeText(RegisterActivity.this, "E-mail is empty", Toast.LENGTH_SHORT).show();
}
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if(success){
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else{
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username, pw, email, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
registerrequest.java:
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://hash.host22.com/register.php";
private Map<String, String> params;
public RegisterRequest(String username, String pw, String email, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username", username);
params.put("pw", pw);
params.put("email", email);
}
@Override
public Map<String, String> getParams() {
return params;
}
}
register.php:
if(isset($_POST['bRegister'])) {
if (empty($_POST["username"])) {
echo"Fill in username to sign up";
} else {
if (empty($_POST["pw"])) {
echo"Fill in password to sign up";
} else {
if (empty($_POST["pw2"])) {
echo"Confirm password to sign up";
} else {
if (empty($_POST["email"])) {
echo"Fill in email to sign up";
} else {
if ($_POST['pw'] == $_POST['pw2']) {
$username = mysqli_real_escape_string($con, $_POST["username"]);
$pw= mysqli_real_escape_string($con, $_POST["pw"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$result = mysqli_query($con ,"SELECT * FROM users WHERE username='" . $username . "'");
if(mysqli_num_rows($result) > 0)
{
echo "Username exists";
} else {
$result2 = mysqli_query($con ,"SELECT * FROM users WHERE email='" . $email. "'");
if(mysqli_num_rows($result2) > 0)
{
echo "Email exist";
} else {
$pw = password_hash($pw, PASSWORD_BCRYPT, array('cost' => 14));
$sql = "INSERT INTO users (username, pw, email) VALUES('" . $username . "', '" . $pw . "', '" . $email . "')";
if(mysqli_query($con, $sql)){
// if insert checked as successful echo username and password saved successfully
echo"success";
}else{
echo mysqli_error($con);
}
} } } else{
echo "The passwords do not match."; // and send them back to registration page
}}}}}
}
請幫助謝謝。
我的應用程序上有一個注冊活動,該活動使用一對與您相似的java文件(一個registerActivity和一個registerRequest),但是對於我的php文件,我使用了一些更簡單的方法。 我將其發布在下面,如果需要,可以嘗試一下,或者改編自己的代碼以適合它,但是使用000webhost db對我而言,它的工作時間為100%。
$con = mysqli_connect("host", "username", "password", "db_name");
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$response = array();
$response["success"] = 0;
$email_check = mysqli_query($con, "SELECT * FROM tableName WHERE email = '$email'");
if(mysqli_num_rows($email_check)) {
$response["success"] = 1;
echo json_encode($response);
exit;
}
$statementR = mysqli_prepare($con, "INSERT INTO tableName (name, email, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statementR, "sss", $name, $email, $password);
mysqli_stmt_execute($statementR);
$statement = mysqli_prepare($con, "SELECT * FROM tableName WHERE email = ?");
mysqli_stmt_bind_param($statement, "s", $email);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $user_id, $name, $email, $password);
while(mysqli_stmt_fetch($statement)){
$response["success"] = 2;
$response["user_id"] = $user_id;
$response["name"] = $name;
$response["email"] = $email;
}
echo json_encode($response);
email_check方法檢查是否已存在電子郵件,然后返回帶有整數值的響應,然后由應用程序解釋。
我的php腳本中沒有任何密碼/用戶名檢查,因為這一切都在應用程序端完成,因為它可以防止不必要的數據庫調用(如果您願意,我也可以發布該代碼)。 如果願意,您可以將服務器端數據檢查添加到上面的代碼中。
為您修改了register.php文件:
$con = mysqli_connect("host", "username", "password", "db_name");
$name = $_POST["username"];
$email = $_POST["email"];
$pw = $_POST["pw"];
$response = array();
$response["success"] = 0;
$email_check = mysqli_query($con, "SELECT * FROM users WHERE email = '$email'");
if(mysqli_num_rows($email_check)) {
$response["success"] = 1;
echo json_encode($response);
exit;
}
$statementR = mysqli_prepare($con, "INSERT INTO users (username, pw, email) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statementR, "sss", $username, $pw, $email);
mysqli_stmt_execute($statementR);
$statement = mysqli_prepare($con, "SELECT * FROM users WHERE email = ?");
mysqli_stmt_bind_param($statement, "s", $email);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $username, $pw, $email);
while(mysqli_stmt_fetch($statement)){
$response["success"] = 2;
$response["username"] = $username;
$response["pw"] = $pw;
$response["email"] = $email;
}
echo json_encode($response);
同樣在您的RegisterActivity中,將if(success){...}
行更新為if(success == 2){...}
。
為了清楚起見,這是我的RegisterActivity(與您的非常相似):
public class RegisterActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText registerName = (EditText) findViewById(R.id.registerName);
final EditText registerEmail = (EditText) findViewById(R.id.registerEmail);
final EditText registerPassword = (EditText) findViewById(R.id.registerPassword);
final EditText registerConfirm = (EditText) findViewById(R.id.registerPasswordConfirm);
final Button registerButton = (Button) findViewById(R.id.registerButton);
final TextView registerLogInLink = (TextView) findViewById(R.id.registerLogInLink);
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String name = registerName.getText().toString();
final String email = registerEmail.getText().toString();
final String password = registerPassword.getText().toString();
final String passwordCheck = registerConfirm.getText().toString();
if(name.length() > 1 & email.length() > 5 & password.length() > 5 & password.equals(passwordCheck)) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
System.out.println(response);
JSONObject jsonResponse = new JSONObject(response);
int success = jsonResponse.getInt("success");
System.out.println(jsonResponse);
System.out.println(success);
if (success == 2) {
Integer user_id = jsonResponse.getInt("user_id");
String name = jsonResponse.getString("name");
String email = jsonResponse.getString("email");
UserCredentials.setUserLoggedInStatus(getApplicationContext(), true);
UserCredentials.setLoggedInUserEmail(getApplicationContext(), email);
UserCredentials.setLoggedInUserName(getApplicationContext(), name);
UserCredentials.setLoggedInUserID(getApplicationContext(), user_id);
Intent intent = new Intent(RegisterActivity.this, MainScreen.class);
RegisterActivity.this.startActivity(intent);
} else if (success == 1) {
AlertDialog.Builder alertMessage = new AlertDialog.Builder(RegisterActivity.this);
alertMessage.setMessage("Registration failed, email already registered.")
.setNegativeButton("Try again", null)
.create()
.show();
} else {
AlertDialog.Builder alertMessage = new AlertDialog.Builder(RegisterActivity.this);
alertMessage.setMessage("Registration failed, please try again")
.setNegativeButton("Try again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
RegisterActivity.this.recreate();}})
.create().show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, email, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
} else if(name.length() > 1 & email.length() <= 5 & password.length() <=5) {
AlertDialog.Builder alertMessage = new AlertDialog.Builder(RegisterActivity.this);
alertMessage.setMessage("Registration failed, email and password invalid. Passwords must be more than 5 characters.")
.setNegativeButton("Retry", null)
.create()
.show();
} else if(name.length() > 1 & email.length() <= 5 & password.length() > 5) {
AlertDialog.Builder alertMessage = new AlertDialog.Builder(RegisterActivity.this);
alertMessage.setMessage("Registration failed, email invalid.")
.setNegativeButton("Retry", null)
.create()
.show();
} else if(name.length() > 1 & email.length() > 5 & password.length() <= 5) {
AlertDialog.Builder alertMessage = new AlertDialog.Builder(RegisterActivity.this);
alertMessage.setMessage("Registration failed, invalid password. Passwords must be more than 5 characters.")
.setNegativeButton("Retry", null)
.create()
.show();
} else if(name.length() <= 1 & email.length() <= 5 & password.length() <=5) {
AlertDialog.Builder alertMessage = new AlertDialog.Builder(RegisterActivity.this);
alertMessage.setMessage("Registration failed, all credentials invalid.")
.setNegativeButton("Retry", null)
.create()
.show();
} else if(name.length() <= 1 & email.length() <= 5 & password.length() > 5) {
AlertDialog.Builder alertMessage = new AlertDialog.Builder(RegisterActivity.this);
alertMessage.setMessage("Registration failed, name and email invalid.")
.setNegativeButton("Retry", null)
.create()
.show();
} else if(name.length() <= 1 & email.length() > 5 & password.length() <= 5) {
AlertDialog.Builder alertMessage = new AlertDialog.Builder(RegisterActivity.this);
alertMessage.setMessage("Registration failed, name and password invalid. Passwords must be more than 5 characters.")
.setNegativeButton("Retry", null)
.create()
.show();
} else if(name.length() > 1 & email.length() > 5 & password.length() > 5 & !password.equals(passwordCheck)) {
AlertDialog.Builder alertMessage = new AlertDialog.Builder(RegisterActivity.this);
alertMessage.setMessage("Registration failed, passwords do not match.")
.setNegativeButton("Retry", null)
.create()
.show();
} else {
AlertDialog.Builder alertMessage = new AlertDialog.Builder(RegisterActivity.this);
alertMessage.setMessage("Something went wrong, please try again.")
.setNegativeButton("Retry", null)
.create()
.show();
}
}
});
registerLogInLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent LogInIntent = new Intent(RegisterActivity.this, LogInActivity.class);
RegisterActivity.this.startActivity(LogInIntent);
}
});
您可以忽略alertDialogs,除非您需要自定義警報,在這種情況下,可以隨意復制它們。 還要確保您的RegisterRequest文件正在連接到正確的URL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.