실행화면


  1. 메인 화면입니다. 여기서 Member Registration을 누릅니다.



  1. 아이디값에 abcd를 입력후 CHECK ID를 누릅니다.



  1. 해당 아이디를 사용할수있다고 나오네요


  1. 모든 항목을 입력해주고 REGISTER 버튼을 누릅니다.


  1. 다시 첫화면으로 돌아가게됩니다.


  1. 데이터베이스를 확인해보면 방금 입력한 abcd 계정이 정상적으로 생성되었음을 알 수 있습니다.


  1. 만약 abcd란 아이디로 다시 회원가입을 하려고 하면 다음과 같이 이미 사용중인 아이디라고 출력됩니다.





저번 3번째 강의인 회원 데이터베이스 구축에서 오류가 있어서 다음과 같이 UserValidate.php 파일을 다음과 같이 수정합니다.


UserValidate.php


<?php

    $con = mysqli_connect('localhost', 'root', 'qwer1234', 'registration');

     $userID = $_POST["userID"];

     $statement = mysqli_prepare($con, "SELECT userID FROM USER WHERE userID = ?");

     //위에서 * 하면 mysqli_stmt_bind_result에서 에러가 나서 정정함

     mysqli_stmt_bind_param($statement, "s", $userID);

     mysqli_stmt_execute($statement);

     mysqli_stmt_store_result($statement);//결과를 클라이언트에 저장함

     mysqli_stmt_bind_result($statement, $userID);//결과를 $userID 바인딩함

     $response = array();

     $response["success"] = true;

     while(mysqli_stmt_fetch($statement)){

       $response["success"] = false;//회원가입불가를 나타냄

       $response["userID"] = $userID;

     }

     //데이터베이스 작업이 성공 혹은 실패한것을 알려줌

     echo json_encode($response);

?>


아래 파일에 colorWarning 과 colorGray를 추가시켜줍니다.


values/colors.xml


<?xml version="1.0" encoding="utf-8"?>

<resources>

    <color name="colorPrimary">#039BE5</color>

    <color name="colorPrimaryDark">#0277BD</color>

    <color name="colorAccent">#546E7A</color>

    <color name="colorWarning">#ED00CB</color>

    <color name="colorGray">#8C8C8C</color>

</resources>


layout/activity_register.xml


기존 레이아웃에서 입력한 id를 검증하기 위한 버튼을 추가해줍니다. 


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.kch.registration_v4.RegisterActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="@color/colorPrimary"
            >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Member Registration"
                android:textColor="#ffffff"
                android:textSize="30dp"
                android:textStyle="bold"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="50dp"
                android:layout_gravity="center"
                >

                <EditText
                    android:layout_width="190dp"
                    android:layout_height="wrap_content"
                    android:hint="ID"
                    android:layout_gravity="center"
                    android:padding="10dp"
                    android:textColor="#ffffff"
                    android:textColorHint="#ffffff"
                    android:id="@+id/idText"
                    android:drawableStart="@drawable/ic_person_black_24dp"
                    android:drawableLeft="@drawable/ic_person_black_24dp"
                    android:layout_marginRight="10dp"
                    android:background="@color/colorPrimary"
                    />
               
                <Button
                    android:layout_width="80dp"
                    android:layout_height="40dp"
                    android:textSize="15dp"
                    android:textStyle="bold"
                    android:background="@color/colorWarning"
                    android:text="Check ID"
                    android:layout_gravity="center"
                    android:id="@+id/validateButton"
                    android:textColor="#ffffff"/>


            </LinearLayout>

            <EditText
                android:inputType="textPassword"
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:hint="PASSWORD"
                android:layout_gravity="center"
                android:padding="10dp"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                android:id="@+id/passwordText"
                android:drawableStart="@drawable/ic_lock_outline_black_24dp"
                android:drawableLeft="@drawable/ic_lock_outline_black_24dp"
                android:layout_marginTop="10dp"
                android:background="@color/colorPrimary"
                />

            <EditText
                android:inputType="text"
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:hint="E-mail"
                android:layout_gravity="center"
                android:padding="10dp"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                android:id="@+id/emailText"
                android:drawableStart="@drawable/ic_mail_outline_black_24dp"
                android:drawableLeft="@drawable/ic_mail_outline_black_24dp"
                android:layout_marginTop="10dp"
                android:background="@color/colorPrimary"
                />
           
            <RadioGroup
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:id="@+id/genderGroup"
                android:layout_gravity="center_horizontal"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                >
                <RadioButton
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:text="female"
                    android:id="@+id/genderWoman"
                    android:layout_weight="1"
                    android:checked="true"
                    />

                <RadioButton
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:text="male"
                    android:id="@+id/genderMan"
                    android:layout_weight="1"
                    />
            </RadioGroup>

            <Spinner
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="10dp"
                android:id="@+id/majorSpinner"
                ></Spinner>

            <Button
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:textStyle="bold"
                android:textColor="#ffffff"
                android:background="@color/colorPrimary"
                android:text="Register"
                android:layout_marginTop="10dp"
                android:layout_gravity="center"
                android:id="@+id/registerButton"
                />


        </LinearLayout>

    </LinearLayout>



</LinearLayout>


RegisterRequest.java


해당 클래스는  URL에 POST방식으로 파라미터들을 전송하는 역할을 수행합니다. 여기서는 회원가입정보를 PHP서버에 보내서 데이터베이스에 저장시키게합니다.


package com.example.kch.registration_v4;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

/**
* Created by kch on 2018. 5. 14..
*/

public class RegisterRequest extends StringRequest {

    final static private String URL = "http://10.0.2.2:8080/registration/UserRegister.php";
    private Map<String, String> parameters;

    public RegisterRequest(String userID, String userPassword, String userGender, String userMajor, String userEmail, Response.Listener<String> listener){
        super(Method.POST, URL, listener, null);//해당 URL에 POST방식으로 파마미터들을 전송함
        parameters = new HashMap<>();
        parameters.put("userID", userID);
        parameters.put("userPassword", userPassword);
        parameters.put("userGender", userGender);
        parameters.put("userMajor", userMajor);
        parameters.put("userEmail", userEmail);

    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return parameters;
    }
}

ValidateRequest.java


해당 클래스도 아래 URL에 POST방식으로 파라미터들을 전송합니다. 여기서는 아이디값이 이미 가입된 아이디인지 검증합니다.


package com.example.kch.registration_v4;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

/**
* Created by kch on 2018. 5. 14..
*/

public class ValidateRequest extends StringRequest {

    final static private String URL = "http://10.0.2.2:8080/registration/UserValidate.php";
    private Map<String, String> parameters;

    public ValidateRequest(String userID, Response.Listener<String> listener){
        super(Method.POST, URL, listener, null);//해당 URL에 POST방식으로 파마미터들을 전송함
        parameters = new HashMap<>();
        parameters.put("userID", userID);
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return parameters;
    }
}




RegisterActivity.java


각 버튼에 대해서 객체를 생성한뒤 리스너를 연결해줍니다. 또한 volley라이브러리를 활용해서 php서버와 통신하는 부분을 구현합니다.


package com.example.kch.registration_v4;

import android.support.annotation.IdRes;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

public class RegisterActivity extends AppCompatActivity {

    private ArrayAdapter adapter;
    private Spinner spinner;
    private String userID;
    private String userPassword;
    private String userGender;
    private String userMajor;
    private String userEmail;
    private AlertDialog dialog;
    private boolean validate = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        //스피너 객체 선언 및 리소스를 가져오는 부분
        spinner = (Spinner)findViewById(R.id.majorSpinner);
        adapter = ArrayAdapter.createFromResource(this, R.array.major, android.R.layout.simple_dropdown_item_1line);
        spinner.setAdapter(adapter);

        final EditText idText = (EditText)findViewById(R.id.idText);
        final EditText passwordText = (EditText)findViewById(R.id.passwordText);
        final EditText emailText = (EditText)findViewById(R.id.emailText);

        RadioGroup genderGroup = (RadioGroup)findViewById(R.id.genderGroup);
        int genderGroupID = genderGroup.getCheckedRadioButtonId();
        userGender = ((RadioButton)findViewById(genderGroupID)).getText().toString();//초기화 값을 지정해줌

        //라디오버튼이 눌리면 값을 바꿔주는 부분
        genderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                RadioButton genderButton = (RadioButton)findViewById(i);
                userGender = genderButton.getText().toString();
            }
        });

        //회원가입시 아이디가 사용가능한지 검증하는 부분
        final Button validateButton = (Button)findViewById(R.id.validateButton);
        validateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userID = idText.getText().toString();
                if(validate){
                    return;//검증 완료
                }
                //ID 값을 입력하지 않았다면
                if(userID.equals("")){
                    AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                    dialog = builder.setMessage("ID is empty")
                            .setPositiveButton("OK", null)
                            .create();
                    dialog.show();
                    return;
                }


                //검증시작
                Response.Listener<String> responseListener = new Response.Listener<String>(){

                    @Override
                    public void onResponse(String response) {
                        try{
                            Toast.makeText(RegisterActivity.this, response, Toast.LENGTH_LONG).show();

                            JSONObject jsonResponse = new JSONObject(response);
                            boolean success = jsonResponse.getBoolean("success");
                            if(success){//사용할 수 있는 아이디라면
                                AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                dialog = builder.setMessage("you can use ID")
                                        .setPositiveButton("OK", null)
                                        .create();
                                dialog.show();
                                idText.setEnabled(false);//아이디값을 바꿀 수 없도록 함
                                validate = true;//검증완료
                                idText.setBackgroundColor(getResources().getColor(R.color.colorGray));
                                validateButton.setBackgroundColor(getResources().getColor(R.color.colorGray));
                            }else{//사용할 수 없는 아이디라면
                                AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                dialog = builder.setMessage("alreay used ID")
                                        .setNegativeButton("OK", null)
                                        .create();
                                dialog.show();
                            }

                        }
                        catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                };//Response.Listener 완료

                //Volley 라이브러리를 이용해서 실제 서버와 통신을 구현하는 부분
                ValidateRequest validateRequest = new ValidateRequest(userID, responseListener);
                RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                queue.add(validateRequest);
            }
        });


        //회원 가입 버튼이 눌렸을때
        Button registerButton = (Button)findViewById(R.id.registerButton);
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userID = idText.getText().toString();
                String userPassword = passwordText.getText().toString();
                String userMajor = spinner.getSelectedItem().toString();
                String userEmail = emailText.getText().toString();

                //ID 중복체크를 했는지 확인함
                if(!validate){
                    AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                    dialog = builder.setMessage("First Check ID plz")
                            .setNegativeButton("OK", null)
                            .create();
                    dialog.show();
                    return;
                }

                //한칸이라도 빠뜨렸을 경우
                if(userID.equals("")||userPassword.equals("")||userMajor.equals("")||userEmail.equals("")||userGender.equals("")){
                    AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                    dialog = builder.setMessage("Empty text exist")
                            .setNegativeButton("OK", null)
                            .create();
                    dialog.show();
                    return;
                }

                //회원가입 시작
                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){//사용할 수 있는 아이디라면
                                AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                dialog = builder.setMessage("Register Your ID")
                                        .setPositiveButton("OK", null)
                                        .create();
                                dialog.show();
                                finish();//액티비티를 종료시킴(회원등록 창을 닫음)
                            }else{//사용할 수 없는 아이디라면
                                AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                dialog = builder.setMessage("Register fail")
                                        .setNegativeButton("OK", null)
                                        .create();
                                dialog.show();
                            }

                        }
                        catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                };//Response.Listener 완료

                //Volley 라이브러리를 이용해서 실제 서버와 통신을 구현하는 부분
                RegisterRequest registerRequest = new RegisterRequest(userID, userPassword, userGender, userMajor, userEmail, responseListener);
                RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                queue.add(registerRequest);


            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(dialog != null){
            dialog.dismiss();
            dialog = null;
        }
    }
}






블로그 이미지

가카리

소프트웨어와 하드웨어 프로그래밍, 취업 및 직장생활 전문 블로그