관리 메뉴

나만을 위한 블로그

[Android] Volley를 이용한 회원가입, 로그인 기능 구현(with MySQL, PHP) 본문

Android

[Android] Volley를 이용한 회원가입, 로그인 기능 구현(with MySQL, PHP)

참깨빵위에참깨빵 2020. 1. 31. 21:51
728x90
반응형

※ 레트로핏을 이용한 회원가입, 로그인 기능 구현도 확인하고 싶다면 아래 포스팅 참고

onlyfor-me-blog.tistory.com/276

 

[Android] 레트로핏을 이용한 회원가입, 로그인 기능 구현 (with MySQL, PHP)

※ 아래 내용은 예제 수준의 내용이기 때문에 커스텀하기 전에 코드를 반드시 이해한 다음 쓰자. 2020.12.12 - 모든 코드 정상 작동 확인 예전에 Volley를 통해 회원가입, 로그인 기능을 구현하는 포

onlyfor-me-blog.tistory.com

 

※ 이 글은 AWS 우분투 18.04 EC2 인스턴스를 만들고 작업한 내용임

※ 이 글은 MySQL DB에 회원가입 정보를 저장하고, 로그인할 때 MySQL에 저장된 데이터를 읽어서 로그인하며 PHP 코드를 사용함

이 글에서 사용한 MySQL 외부 접속 툴은 하이디 SQL임

 

참고한 영상 : https://www.youtube.com/watch?v=R21YgEjSwPk

 

영상에 소스코드가 없어서 기록하고자 쓰게 됐다.

 

 

- Volley?

 

https://developer.android.com/training/volley

 

Volley 개요  |  Android 개발자  |  Android Developers

Volley는 Android 앱의 네트워킹을 더 쉽고, 무엇보다도 더 빠르게 하는 HTTP 라이브러리입니다. Volley는 GitHub에서 사용할 수 있습니다. Volley를 사용하면 다음과 같은 이점이 있습니다. 네트워크 요청의 자동 예약. 여러 개의 동시 네트워크 연결. 표준 HTTP 캐시 일관성을 갖춘 투명한 디스크 및 메모리 응답 캐싱. 요청 우선순위 지정 지원. 취소 요청 API. 단일 요청을 취소하거나 취소할 요청의 블록 또는 범위를 설정할 수

developer.android.com

- Volley는 안드로이드 앱의 네트워킹을 더 쉽고 빠르게 하는 HTTP 라이브러리다. 이 한 문장만 중요해 보이고 나머지는 아직까진 딱히 와닿지 않는 장점들과 사용법을 나열해놓았다. 20.01.31 기준 최신 Volley를 사용하려면 앱 수준 gradle에 이 문장을 넣어줘야 한다.

implementation 'com.android.volley:volley:1.1.1'

 

 

https://qlyh8.tistory.com/93

 

Volley 사용하기 - (1)

출처: https://www.edwith.org/boostcourse-android/lecture/17091/ 1. Volley Volley 라이브러리는 웹 요청과 응답을 단순화시키기 위해 만들어진 라이브러리들 중의 하나이다. Volley를 사용하는 방법은 Request..

qlyh8.tistory.com

Volley 라이브러리는 웹 요청과 응답을 단순화시키기 위해 만들어진 라이브러리 중 하나다. Volley 사용법은 Request 객체를 만들고 이 Request 객체를 Request Queue에 넣어주면 된다. Request Queue는 알아서 웹 서버에 요청하고 응답받기 때문에 쓰레드를 신경쓰지 않아도 된다.

 

 

코드 기록 이전에 내가 사용한 사전 준비물들을 기록한다.

- 안드로이드 스튜디오(프래그먼트 사용)

- AWS 우분투 18.04 LTS EC2

- 비주얼 스튜디오 코드(코드 에디터, ftp-simple 확장 프로그램 사용해 AWS EC2에 연결해 php 코드 편집)

 

 

1. 먼저 안드로이드 스튜디오 디벨로퍼에서 말했듯 앱 수준 gradle에 의존성을 한 문장 추가해줘야 한다.

implementation 'com.android.volley:volley:1.1.1'
// 아래의 의존성들은 영상에서 사용하는 EditText 등을 쓰기 위해 필요하다.
implementation 'com.google.android.material:material:1.0.0-alpha1'
implementation 'com.rengwuxian.materialedittext:library:2.1.4'

 

참고로 난 최소 SDK 버전은 15, 타겟 SDK 버전은 29로 설정했다.

 

1-1. res/values/styles.xml을 열어 아래의 style 코드를 추가한다.

 

<style name="menustyle"
        parent="Theme.AppCompat.Light">
        <item name="android:background">@color/colorPrimaryDark</item>
    </style>

그리고 xml 폴더에 bar_layout.xml 파일을 하나 만들고 아래 코드를 넣는다.

아래 코드가 에러없이 돌아가려면, 의존성에 implementation 'com.google.android.material:material:1.0.0-alpha1' 문장을 추가해줘야 한다. 이 코드를 입력하면 화면 상단에 background 속성에 적힌 색대로 직사각형 모양의 공간이 생겨난다.

 

<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@color/colorPrimaryDark"
    style="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/menustyle"
    android:id="@+id/toolbar">

</androidx.appcompat.widget.Toolbar>

그리고 values 폴더의 strings.xml 파일의 내용을 추가한다.

 

<resources>
    <string name="prefLoginState">loginstate</string>
</resources>

 

마지막으로 매니페스트를 좀 건드려야 한다.

안드로이드 9 파이 버전부터는 HTTP가 아니라 HTTPS를 쓰라고 강제했기 때문에(https://onlyfor-me-blog.tistory.com/118 참고), 매니페스트 속성을 추가해서 HTTP에서 작업할 수 있도록 해야 한다.

 

그 전에 res 폴더를 우클릭 후 New -> Folder -> xml resources folder를 눌러 xml 폴더를 만들고, 그 안에 network_security_config 파일을 만들고 아래의 코드를 추가해준다.

 

<?xml version="1.0" encoding="utf-8"?>
<network-security-config xmlns:tools="http://schemas.android.com/tools">
    <base-config cleartextTrafficPermitted="true"
        tools:ignore="InsecureBaseConfiguration" />
</network-security-config>

그리고 매니페스트에 아래의 속성들을 추가해준다.

 

android:networkSecurityConfig="@xml/network_security_config" // 위에서 만든 network_security_config 파일을 사용한다.
android:usesCleartextTraffic="true"

 

원래는 저 둘 중 하나만 써도 된다지만 둘 다 써도 문제는 없어서 난 둘 다 썼다. 빌드하면서 문제는 생기지 않았다.

 

2. 다음의 파일들을 만들어준다.

 

- 액티비티 : RegisterActivity, AppStartActivity(xml도 같이 있어야 한다)

- 자바 클래스 파일 : MySingleton

- xml 파일 : bar_layout.xml(위에서 이미 만들었다)

 

2-1. DB 설정은 아래와 같이 한다. DB 이름은 users_database고 테이블 이름은 users_table이다.

 

 

3. 다음부터는 각 파일별 코드들이다. 먼저 XML 파일들의 코드들이다.

 

// activity_app_start.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".AppStartActivity">

    <include
        android:id="@+id/toolbar"
        layout="@layout/bar_layout"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Welcome to App Start Activity"
        android:gravity="center"
        android:textSize="20dp"
        android:textStyle="bold"
        android:textColor="@color/colorPrimaryDark"
        android:layout_marginTop="20dp"/>

    <Button
        android:id="@+id/logout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Logout"
        android:textAllCaps="false"
        android:background="@color/colorPrimaryDark"
        android:textColor="@android:color/white"
        android:layout_marginTop="20dp"/>

</LinearLayout>
// activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:gravity="center"
        android:textSize="20dp"
        android:textStyle="bold"
        android:textColor="@color/colorPrimaryDark"
        android:layout_marginTop="20dp"/>

    <com.rengwuxian.materialedittext.MaterialEditText
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email"
        app:met_floatingLabel="normal"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:padding="5dp"
        android:textColor="@color/colorPrimaryDark"/>

    <com.rengwuxian.materialedittext.MaterialEditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        app:met_floatingLabel="normal"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:padding="5dp"
        android:textColor="@color/colorPrimaryDark"/>

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Keep Me Logged In"
        android:textColor="@color/colorPrimaryDark"
        android:buttonTint="@color/colorPrimaryDark"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"/>

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:textAllCaps="false"
        android:background="@color/colorPrimaryDark"
        android:textColor="@android:color/white"
        android:layout_marginTop="20dp"/>

    <Button
        android:id="@+id/register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:textAllCaps="false"
        android:background="@color/colorPrimaryDark"
        android:textColor="@android:color/white"
        android:layout_marginTop="20dp"/>

</LinearLayout>
// activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <include
        android:id="@+id/toolbar"
        layout="@layout/bar_layout"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_below="@id/toolbar">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Register New Account"
            android:gravity="center"
            android:textSize="20dp"
            android:textStyle="bold"
            android:textColor="@color/colorPrimaryDark"
            android:layout_marginTop="20dp"/>

        <com.rengwuxian.materialedittext.MaterialEditText
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="User Name"
            app:met_floatingLabel="normal"
            android:layout_marginTop="10dp"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="20dp"
            android:padding="5dp"
            android:textColor="@color/colorPrimaryDark"/>

        <com.rengwuxian.materialedittext.MaterialEditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"
            app:met_floatingLabel="normal"
            android:layout_marginTop="10dp"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="20dp"
            android:padding="5dp"
            android:textColor="@color/colorPrimaryDark"/>

        <com.rengwuxian.materialedittext.MaterialEditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"
            app:met_floatingLabel="normal"
            android:layout_marginTop="10dp"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="20dp"
            android:padding="5dp"
            android:textColor="@color/colorPrimaryDark"/>

        <com.rengwuxian.materialedittext.MaterialEditText
            android:id="@+id/mobile"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Mobile"
            app:met_floatingLabel="normal"
            android:layout_marginTop="10dp"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="20dp"
            android:padding="5dp"
            android:textColor="@color/colorPrimaryDark"/>

        <RadioGroup
            android:id="@+id/radiogp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Male"
                android:id="@+id/male"
                android:textColor="@color/colorPrimaryDark"
                android:buttonTint="@color/colorPrimaryDark"/>

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Female"
                android:id="@+id/female"
                android:textColor="@color/colorPrimaryDark"
                android:buttonTint="@color/colorPrimaryDark"/>

        </RadioGroup>

        <Button
            android:id="@+id/register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Register"
            android:textAllCaps="false"
            android:background="@color/colorPrimaryDark"
            android:textColor="@android:color/white"
            android:layout_marginTop="20dp"/>

    </LinearLayout>

</RelativeLayout>

 

다음은 자바 클래스 파일들의 코드들이다.

 

// MySingleton.class

import android.content.Context;

import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.Volley;

public class MySingleton {

    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private Context mCtx;

    public MySingleton(Context mCtx) {
        this.mCtx = mCtx;
        mRequestQueue = getmRequestQueue();
    }

    public RequestQueue getmRequestQueue() {
        if (mRequestQueue == null) {
            Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 1024*1024);
            Network network = new BasicNetwork(new HurlStack());
            mRequestQueue = new RequestQueue(cache, network);
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public static synchronized MySingleton getmInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(context);
        }

        return mInstance;
    }

    public <T> void addToRequestQueue(Request<T> request) {
        mRequestQueue.add(request);
    }

}
// AppStartActivity.class

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class AppStartActivity extends AppCompatActivity {

    Button logout;

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("App Start Activity");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        final SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", 0);

        logout = findViewById(R.id.logout);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(getResources().getString(R.string.prefLoginState), "loggedout");
                editor.apply();
                startActivity(new Intent(AppStartActivity.this, MainActivity.class));
                finish();
            }
        });
    }
}
// MainActivity.class

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.rengwuxian.materialedittext.MaterialEditText;

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

public class MainActivity extends AppCompatActivity {

    MaterialEditText email, password;
    Button login, register;
    CheckBox loginState;
    SharedPreferences sharedPreferences;

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

        sharedPreferences = getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
        loginState = findViewById(R.id.checkbox);
        login = findViewById(R.id.login);
        register = findViewById(R.id.register);
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                startActivity(new Intent(MainActivity.this, RegisterActivity.class));
                finish();
            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                String txtEmail = email.getText().toString();
                String txtPassword = password.getText().toString();
                if (TextUtils.isEmpty(txtEmail) || TextUtils.isEmpty(txtPassword)) {
                    Toast.makeText(MainActivity.this, "All fields required", Toast.LENGTH_SHORT).show();
                } else {
                    login(txtEmail, txtPassword);
                }
            }
        });

        String loginStatus = sharedPreferences.getString(getResources().getString(R.string.prefLoginState), "");
        if (loginStatus.equals("loggedin")) {
            startActivity(new Intent(MainActivity.this, AppStartActivity.class));
        }

    }

    private void login(final String email, final String password) {
        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(false);
        progressDialog.setTitle("Registering New Account");
        progressDialog.show();

        String uRl = "http://웹서버주소/loginregister/login.php";
        StringRequest request = new StringRequest(Request.Method.POST, uRl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response)
            {
                if (response.equals("Login Success")) {
                    progressDialog.dismiss();
                    Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    if (loginState.isChecked()) {
                        editor.putString(getResources().getString(R.string.prefLoginState), "loggedin");
                    }
                    else {
                        editor.putString(getResources().getString(R.string.prefLoginState), "loggedout");
                    }
                    editor.apply();
                    startActivity(new Intent(MainActivity.this, AppStartActivity.class));
                }

                else {
                    progressDialog.dismiss();
                    Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError
            {
                HashMap<String, String> param = new HashMap<>();
                param.put("email", email);
                param.put("psw", password);

                return param;
            }
        };

        request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                                                      DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        MySingleton.getmInstance(MainActivity.this).addToRequestQueue(request);

    }

}
// RegisterActivity.class

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.rengwuxian.materialedittext.MaterialEditText;

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

public class RegisterActivity extends AppCompatActivity {

    MaterialEditText userName, email, password, mobile;
    RadioGroup radioGroup;
    Button register;

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

        userName = findViewById(R.id.username);
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
        mobile = findViewById(R.id.mobile);
        radioGroup = findViewById(R.id.radiogp);
        register = findViewById(R.id.register);

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                String txtUserName = userName.getText().toString();
                String txtEmail = email.getText().toString();
                String txtPassword = password.getText().toString();
                String txtMobile = mobile.getText().toString();

                if (TextUtils.isEmpty(txtUserName) || TextUtils.isEmpty(txtEmail) || TextUtils.isEmpty(txtPassword)
                || TextUtils.isEmpty(txtMobile)) {
                    Toast.makeText(RegisterActivity.this, "All fields required", Toast.LENGTH_SHORT).show();
                } else {
                    int genderId = radioGroup.getCheckedRadioButtonId();
                    RadioButton selected_Gender = radioGroup.findViewById(genderId);
                    if (selected_Gender == null) {
                        Toast.makeText(RegisterActivity.this, "Select gender Please", Toast.LENGTH_SHORT).show();
                    } else {
                        String selectGender = selected_Gender.getText().toString();
                        registerNewAccount(txtUserName, txtEmail, txtPassword, txtMobile, selectGender);
                    }
                }
            }
        });
    }

    private void registerNewAccount(final String username, final String email, final String password,
                                    final String mobile, final String gender) {

        final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this);
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(false);
        progressDialog.setTitle("Registering New Account");
        progressDialog.show();

        String uRl = "http://웹서버주소/loginregister/register.php";
        StringRequest request = new StringRequest(Request.Method.POST, uRl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response)
            {
                if (response.equals("Successfully Registered")) {
                    progressDialog.dismiss();
                    Toast.makeText(RegisterActivity.this, response, Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                    finish();
                } else {
                    progressDialog.dismiss();
                    Toast.makeText(RegisterActivity.this, response, Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                progressDialog.dismiss();
                Toast.makeText(RegisterActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError
            {
                HashMap<String, String> param = new HashMap<>();
                param.put("username", username);
                param.put("email", email);
                param.put("psw", password);
                param.put("mobile", mobile);
                param.put("gender", gender);

                return param;
            }
        };

        request.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                                                      DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        MySingleton.getmInstance(RegisterActivity.this).addToRequestQueue(request);

    }

}

 

4. 마지막으로 php 코드들이다. 만들어야 할 php 파일은 conn.php / login.php / register.php 3개다.

 

// conn.php

<?php
 $db_name = "users_database"; 		// DB 이름
 $username = "root";		  		// 사용자 이름
 $password = "MySQL 비밀번호"; 		 // MySQL 비밀번호
 $servername = "퍼블릭 IPv4 주소";	// AWS EC2 인스턴스에 할당된 퍼블릭 IPv4 주소. localhost는 안해봤지만 될 것 같다.
 
 $conn = mysqli_connect($servername, $username, $password, $db_name);
 
?>
// login.php

<?php
 require "conn.php";

 $email = $_POST["email"];
 $password = $_POST["psw"];
 $isValidEmail = filter_var($email, FILTER_VALIDATE_EMAIL);

 if ($conn) {
     

     if ($isValidEmail === false) {
         echo "This Email is not valid";
     } else {
         
        $sqlCheckEmail = "SELECT * FROM users_table WHERE email LIKE '$email'";
        $usernameQuery = mysqli_query($conn, $sqlCheckEmail);

        if (mysqli_num_rows($usernameQuery) > 0) {
            
            $sqlLogin = "SELECT * FROM users_table WHERE email LIKE '$email' AND password LIKE '$password'";
            $loginQuery = mysqli_query($conn, $sqlLogin);

            if (mysqli_num_rows($loginQuery) > 0) {
                echo "Login Success";
            } else {
                echo "Wrong Password";
            }

        } else {
            echo "This Email is not registered";
        }

     }
 } else {
     echo "Connection Error";
 }

?>
// register.php

<?php
 require "conn.php";

 $username = $_POST["username"];
 $email = $_POST["email"];
 $password = $_POST["psw"];
 $mobile = $_POST["mobile"];
 $gender = $_POST["gender"];

//  아래는 미리 박아둔 데이터들을 써서 앱이 잘 작동하는지 확인하려고 임의로 만든 변수들이다.
//  $username = "test";
//  $email = "test@naver.com";
//  $password = "1234567";
//  $mobile = "011000000";
//  $gender = "Male";

 $isValidEmail = filter_var($email, FILTER_VALIDATE_EMAIL);
 if ($conn) {
     
    if ($isValidEmail === false) {

        echo "This Email is not valid";
    }
    else {

        $sqlCheckUsername = "SELECT * FROM users_table WHERE username LIKE '$username'";
        $usernameQuery = mysqli_query($conn, $sqlCheckUsername);

        $sqlCheckEmail = "SELECT * FROM users_table WHERE email LIKE '$email'";
        $usernameQuery = mysqli_query($conn, $sqlCheckEmail);


        if (mysqli_num_rows($usernameQuery) > 0) {
            echo "User name is already used, type another one";
        } else if (mysqli_num_rows($usernameQuery) > 0) {
            echo "This email is already registered, type another Email";
        }

        else {

            $sql_register = "INSERT INTO users_table (username, email, password, mobile, gender) VALUES('$username', '$email', '$password', '$mobile', '$gender')";

            if (mysqli_query($conn, $sql_register)) {
                echo "Successfully Registered";
            } else {
                echo "Failed to register";
            }

        }

    }

 }
 else {
     echo "Connection Error";
 }

?>

 

영상에서도 주석을 달아놓지 않아서 분석은 알아서 해야 한다.

이 코드들을 실행하면 Volley를 이용해 안드로이드 앱에서 회원가입 시 입력한 데이터들을 AWS 안의 MySQL DB에 넣을 수 있고, 이 데이터를 토대로 로그인을 할 수 있다.

로그인이 성공한다면, 즉 MySQL에 데이터를 입력하고 이 정보로 로그인이 정상적으로 이뤄진다면 Welcome to App Start Activity 라고 적힌 액티비티로 이동되며 Login success 토스트가 하단에 출력될 것이다.

반응형
Comments