简体   繁体   中英

Android studio sign up not working

I am creating a social network for android with android studio . When I enter text in all of the fields and click Register nothing happens . I previously checked the Android Monitor and it printed that I wasn't using the Internet permission . So I added that in . Now I get no errors and still nothing happens when I click Register . When I click Register , if the registration was successful , the user's info goes into the database and then they go to the login screen . Can someone help me fix this problem ?

Android manifest:

<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
            }}}}}
     }

please help thanks .

I have a registration activity on my app that uses a similar pair of java files as yours (a registerActivity and a registerRequest), but for my php file I used something a bit more simple. I'll post it below, give it a go if you want or adapt your own code to suit it, but it works 100% of the time for me using a 000webhost db.

$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);

The email_check method checks to see whether an email already exists, then returns a response with an integer value which the app then interprets.

There aren't any password/username checks in my php script since that's all done app-side since it prevents unnecessary database calls (I can post that code too if you'd like). You could probably add your server-side data checks to the code above if you want to.

The register.php file modified for you:

$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);

Also in your RegisterActivity, update the line if(success){...} to if(success == 2){...} .

For clarity, here's my RegisterActivity (very similar to yours):

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

        }
});

You can ignore the alertDialogs unless you want custom alerts, in which case feel free to copy them. Also make sure your RegisterRequest file is connecting to the correct URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM