Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

맨땅에 코딩

[Android] 로그인&회원가입 기능(2) - 중복체크(php, 프로젝트 소스코드 포함) 본문

앱 개발/Java

[Android] 로그인&회원가입 기능(2) - 중복체크(php, 프로젝트 소스코드 포함)

맨땅 2022. 12. 23. 11:33

목차

    반응형

     

     

    https://haruvely.tistory.com/32 1편입니다

     

    +) 아이디 중복체크 기능 추가

     

     

     

    <ValidateRequest.java>

    public class ValidateRequest extends StringRequest {
        //서버 url 설정(php파일 연동)
        final static  private String URL="http://ip:port/UserValidate.php";
        private Map<String,String> map;
    
        public ValidateRequest(String userID, Response.Listener<String>listener){
            super(Method.POST,URL,listener,null);
    
            map=new HashMap<>();
            map.put("userID",userID);
        }
    
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            return map;
        }
    }

    ip:port 사용하시는 ip, port 번호로 바꿔주시면 됩니다

     

     

    <activity_register.xml>

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".RegisterActivity">
    
        <EditText
            android:id="@+id/et_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="200dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:ems="10"
            android:hint="아이디"
            android:inputType="textPersonName"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <EditText
            android:id="@+id/et_pass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:hint="비밀번호"
            android:inputType="textPersonName"
            app:layout_constraintEnd_toEndOf="@+id/et_id"
            app:layout_constraintStart_toStartOf="@+id/et_id"
            app:layout_constraintTop_toBottomOf="@+id/et_id" />
    
        <EditText
            android:id="@+id/et_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:hint="이름"
            android:inputType="textPersonName"
            app:layout_constraintEnd_toEndOf="@+id/et_pass"
            app:layout_constraintStart_toStartOf="@+id/et_pass"
            app:layout_constraintTop_toBottomOf="@+id/et_pass" />
    
        <EditText
            android:id="@+id/et_age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:ems="10"
            android:hint="나이"
            android:inputType="textPersonName"
            app:layout_constraintEnd_toEndOf="@+id/et_name"
            app:layout_constraintStart_toStartOf="@+id/et_name"
            app:layout_constraintTop_toBottomOf="@+id/et_name" />
    
        <Button
            android:id="@+id/btn_register"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="회원가입"
            app:layout_constraintEnd_toEndOf="@+id/et_age"
            app:layout_constraintStart_toStartOf="@+id/et_age"
            app:layout_constraintTop_toBottomOf="@+id/et_age" />
    
        <Button
            android:id="@+id/btn_validateCheck"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="200dp"
            android:text="중복체크"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/et_id"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>

     

     

     

    <RegisterActivity.java>

    public class RegisterActivity extends AppCompatActivity {
    
        private EditText et_id, et_pass, et_name, et_age;
        private Button btn_register, btn_validateCheck;
        private AlertDialog dialog;
        private boolean validate = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) { // 액티비티 시작시 처음으로 실행되는 생명주기!
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_register);
    
            // 아이디 값 찾아주기
            et_id = findViewById(R.id.et_id);
            et_pass = findViewById(R.id.et_pass);
            et_name = findViewById(R.id.et_name);
            et_age = findViewById(R.id.et_age);
    
            // 아이디 중복 체크
            btn_validateCheck = findViewById(R.id.btn_validateCheck);
            btn_validateCheck.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String userID = et_id.getText().toString();
                    if (validate) {
                        return; // 검증 완료
                    }
                    if (userID.equals("")) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                        dialog = builder.setMessage("아이디를 입력하세요.").setPositiveButton("확인", null).create();
                        dialog.show();
                        return;
                    }
                    Response.Listener<String> responseListener = new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                Log.d("response1 : ", response);
                                JSONObject jsonResponse = new JSONObject(response);
                                boolean success = jsonResponse.getBoolean("success");
    
                                if (success) {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                    dialog = builder.setMessage("사용할 수 있는 아이디입니다.").setPositiveButton("확인", null).create();
                                    dialog.show();
                                    et_id.setEnabled(false); //아이디값 고정
                                    validate = true; //검증 완료
                                    btn_validateCheck.setBackgroundColor(getResources().getColor(R.color.colorGray));
                                }
                                else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                    dialog = builder.setMessage("이미 존재하는 아이디입니다.").setNegativeButton("확인", null).create();
                                    dialog.show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    ValidateRequest validateRequest = new ValidateRequest(userID,responseListener);
                    RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                    queue.add(validateRequest);
                }
            });
    
            // 회원가입 버튼 클릭 시 수행
            btn_register = findViewById(R.id.btn_register);
            btn_register.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // EditText에 현재 입력되어있는 값을 get(가져온다)해온다.
                    String userID = et_id.getText().toString();
                    String userPass = et_pass.getText().toString();
                    String userName = et_name.getText().toString();
                    int userAge = Integer.parseInt(et_age.getText().toString());
    
                    if(validate) {
                        Response.Listener<String> responseListener = new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                try {
                                    Log.d("response2 : ", response);
                                    JSONObject jsonObject = new JSONObject(response);
                                    boolean success = jsonObject.getBoolean("success");
                                    if (success) { // 회원등록에 성공한 경우
                                        Toast.makeText(getApplicationContext(), "회원 등록에 성공하였습니다.", Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                        startActivity(intent);
                                    } else { // 회원등록에 실패한 경우
                                        Toast.makeText(getApplicationContext(), "회원 등록에 실패하였습니다.", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        };
                        // 서버로 Volley를 이용해서 요청을 함.
                        RegisterRequest registerRequest = new RegisterRequest(userID, userPass, userName, userAge, responseListener);
                        RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                        queue.add(registerRequest);
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                        dialog = builder.setMessage("아이디 중복체크 해주세요.").setNegativeButton("확인", null).create();
                        dialog.show();
                    }
                }
            });
    
        }
    }

     

     

     

    <UserValidate.php>

    <?php
        $con = mysqli_connect("127.0.0.1:3310", "root", "1233", "user");
        mysqli_query($con,'SET NAMES utf8');
    
        $userID = isset($_POST["userID"]) ? $_POST["userID"] : "";
            
        $statement = mysqli_prepare($con, "SELECT * FROM user WHERE userID = ?");
        mysqli_stmt_bind_param($statement, "s", $userID);
        mysqli_stmt_execute($statement);
    
        $response = array();
        $response["success"] = true;
     
        while(mysqli_stmt_fetch($statement)) {
            $response["success"] = false;
            $response["userID"] = $userID;
        }
    
        echo json_encode($response);
    
    ?>

     

     

     

    궁금한 점은 댓글 남겨주세요

     

    감사합니다

     

     

     

     

    반응형