안드로이드 로그인 오픈소스 - andeuloideu logeu-in opeunsoseu

마지막으로 안드로이드에서 회원가입과 로그인 기능을 구현하는 방법에 대해 설명하겠습니다.

우선 안드로이드 스튜디오를 열어봅니다.

안드로이드 로그인 오픈소스 - andeuloideu logeu-in opeunsoseu

Empty Activity를 선택한 후 다음으로 넘어갑니다.

안드로이드 로그인 오픈소스 - andeuloideu logeu-in opeunsoseu

프로젝트 명과 언어를 선택해야하는데
저는 test로 프로젝트 이름을 정하고, Java를 사용하겠습니다.

안드로이드 로그인 오픈소스 - andeuloideu logeu-in opeunsoseu

app -> res -> layout을 우클릭한 후
new 버튼을 클릭하여 Layout resource file을 선택하여 xml 파일을 만들어 줍니다.
혹시 몰라 제가 직접 만든 xml 코드를 공유하겠습니다.

# activity_join.xml (회원가입 화면)




    

    

    

    

    

    

    

    


  • 저의 코드를 참고할 경우
    app -> res -> values -> styles.xml

# styles.xml

app -> res -> values -> color.xml

# color.xml



    #FFC107
    #FF7043
    #FFAB40
    #8C8C8C

안드로이드 로그인 오픈소스 - andeuloideu logeu-in opeunsoseu

color, styles도 동일하게 입력할 경우 이러한 화면이 구성됩니다.

안드로이드 로그인 오픈소스 - andeuloideu logeu-in opeunsoseu

위 화면을 참고하여 class도 만들어 줍니다.

# RegisterRequest.java (회원가입 값 요청)

package com.example.test;

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

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class RegisterRequest extends StringRequest {

    //서버 URL 설정(php 파일 연동)
    final static private String URL = "http://ftp 아이디.dothome.co.kr/Register.php";
    private Map map;
    //private Mapparameters;

    public RegisterRequest(String UserEmail, String UserPwd, String UserName,Response.Listener listener) {
        super(Method.POST, URL, listener, null);

        map = new HashMap<>();
        map.put("UserEmail", UserEmail);
        map.put("UserPwd", UserPwd);
        map.put("UserName", UserName);
      }

    @Override
    protected MapgetParams() throws AuthFailureError {
        return map;
    }
}

# RegisterActivity.java (회원가입 처리)

package com.example.test;

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

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

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

import org.json.JSONException;
import org.json.JSONObject;

public class RegisterActivity extends AppCompatActivity {

    private EditText join_email, join_password, join_name, join_pwck;
    private Button join_button, check_button;
    private AlertDialog dialog;
    private boolean validate = false;

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

        //아이디값 찾아주기
        join_email = findViewById( R.id.join_email );
        join_password = findViewById( R.id.join_password );
        join_name = findViewById( R.id.join_name );
        join_pwck = findViewById(R.id.join_pwck);


        //아이디 중복 체크
        check_button = findViewById(R.id.check_button);
        check_button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                String UserEmail = join_email.getText().toString();
                if (validate) {
                    return; //검증 완료
                }

                if (UserEmail.equals("")) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                    dialog = builder.setMessage("아이디를 입력하세요.").setPositiveButton("확인", null).create();
                    dialog.show();
                    return;
                }

                Response.Listener responseListener = new Response.Listener() {
                    @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("사용할 수 있는 아이디입니다.").setPositiveButton("확인", null).create();
                                dialog.show();
                                join_email.setEnabled(false); //아이디값 고정
                                validate = true; //검증 완료
                                check_button.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(UserEmail, responseListener);
                RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                queue.add(validateRequest);
            }
        });



        //회원가입 버튼 클릭 시 수행
        join_button = findViewById( R.id.join_button );
        join_button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String UserEmail = join_email.getText().toString();
                final String UserPwd = join_password.getText().toString();
                final String UserName = join_name.getText().toString();
                final String PassCk = join_pwck.getText().toString();


                //아이디 중복체크 했는지 확인
                if (!validate) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                    dialog = builder.setMessage("중복된 아이디가 있는지 확인하세요.").setNegativeButton("확인", null).create();
                    dialog.show();
                    return;
                }

                //한 칸이라도 입력 안했을 경우
                if (UserEmail.equals("") || UserPwd.equals("") || UserName.equals("")) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                    dialog = builder.setMessage("모두 입력해주세요.").setNegativeButton("확인", null).create();
                    dialog.show();
                    return;
                }

                Response.Listener responseListener = new Response.Listener() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jsonObject = new JSONObject( response );
                            boolean success = jsonObject.getBoolean( "success" );

                            //회원가입 성공시
                            if(UserPwd.equals(PassCk)) {
                                if (success) {

                                    Toast.makeText(getApplicationContext(), String.format("%s님 가입을 환영합니다.", UserName), Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                    startActivity(intent);

                                    //회원가입 실패시
                                } else {
                                    Toast.makeText(getApplicationContext(), "회원가입에 실패하였습니다.", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                dialog = builder.setMessage("비밀번호가 동일하지 않습니다.").setNegativeButton("확인", null).create();
                                dialog.show();
                                return;
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                };

                //서버로 Volley를 이용해서 요청
                RegisterRequest registerRequest = new RegisterRequest( UserEmail, UserPwd, UserName, responseListener);
                RequestQueue queue = Volley.newRequestQueue( RegisterActivity.this );
                queue.add( registerRequest );
            }
        });
    }
}

RegisterActivity.java 에서
아이디 중복 확인, 비밀번호 일치 확인 기능을 구현했고,
한 칸이라도 빈 칸이 있을 경우 알림창을 통해 입력할 수 있도록 구현, 아이디 중복 체크를 안했을 시에도 알림창이 뜨도록 하였습니다.

package com.example.test;

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

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

public class ValidateRequest extends StringRequest {
    //서버 url 설정(php파일 연동)
    final static  private String URL="http://dodam123.dothome.co.kr/UserValidate.php";
    private Map map;

    public ValidateRequest(String UserEmail, Response.Listener listener){
        super(Method.POST, URL, listener,null);

        map = new HashMap<>();
        map.put("UserEmail", UserEmail);
    }

    @Override
    protected Map getParams() throws AuthFailureError {
        return map;
    }
}

회원가입 구현을 모두 마쳤으니 로그인 기능을 구현하도록 하겠습니다.

#activity_login.xml




    

    

    

    


    

안드로이드 로그인 오픈소스 - andeuloideu logeu-in opeunsoseu

위와 같은 화면이 구성됩니다.

# LoginRequest.java

package com.example.test;

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

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

public class LoginRequest extends StringRequest {

    //서버 URL 설정(php 파일 연동)
    final static private String URL = "http://dodam123.dothome.co.kr/Login.php";
    private Map map;

    public LoginRequest(String UserEmail, String UserPwd, Response.Listener listener) {
        super(Method.POST, URL, listener, null);

        map = new HashMap<>();
        map.put("UserEmail", UserEmail);
        map.put("UserPwd", UserPwd);
    }

    @Override
    protected MapgetParams() throws AuthFailureError {
        return map;
    }
}

# LoginActivity.java

package com.example.test;

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

import androidx.appcompat.app.AppCompatActivity;

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

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {

    private EditText login_email, login_password;
    private Button login_button, join_button;

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

        login_email = findViewById( R.id.login_email );
        login_password = findViewById( R.id.login_password );

        join_button = findViewById( R.id.join_button );
        join_button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent( LoginActivity.this, MainActivity.class );
                startActivity( intent );
            }
        });


        login_button = findViewById( R.id.login_button );
        login_button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String UserEmail = login_email.getText().toString();
                String UserPwd = login_password.getText().toString();

                Response.Listener responseListener = new Response.Listener() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject( response );
                            boolean success = jsonObject.getBoolean( "success" );

                            if(success) {//로그인 성공시

                                String UserEmail = jsonObject.getString( "UserEmail" );
                                String UserPwd = jsonObject.getString( "UserPwd" );
                                String UserName = jsonObject.getString( "UserName" );

                                Toast.makeText( getApplicationContext(), String.format("%s님 환영합니다.", UserName), Toast.LENGTH_SHORT ).show();
                                Intent intent = new Intent( LoginActivity.this, MainActivity.class );

                                intent.putExtra( "UserEmail", UserEmail );
                                intent.putExtra( "UserPwd", UserPwd );
                                intent.putExtra( "UserName", UserName );

                                startActivity( intent );

                            } else {//로그인 실패시
                                Toast.makeText( getApplicationContext(), "로그인에 실패하셨습니다.", Toast.LENGTH_SHORT ).show();
                                return;
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                LoginRequest loginRequest = new LoginRequest( UserEmail, UserPwd, responseListener );
                RequestQueue queue = Volley.newRequestQueue( LoginActivity.this );
                queue.add( loginRequest );

            }
        });
    }
}

로그인 기능 구현도 완료되었습니다.
로그인 성공 시 MainActivity 화면으로 넘어가게 설정하였으니
구현하고 싶은 모습대로 화면 설정하시면 됩니다.

로그인, 회원가입 시 UserName을 받아 환영 문구도 설정하였습니다.
원하는 문구로 변경하시거나 원하는 칼럼을 받아오시면 됩니다.

app -> mainfests -> AndoridMainfest.xml에 들어가셔서

코드를 추가하여 인터넷 권한을 부여합니다.

Gradle Scripts -> build.gradle (Module: app) 에 들어가셔서

implementation 'com.android.volley:volley:1.1.1'//서버통신 관련 라이브러리

코드를 추가해주신 후 Volley를 다운로드 받으시면 됩니다.

위 방법을 하신 후에도 오류가 발생한다면
AndoridMainfest.xml 에 들어가셔서 acticity 들을 추가해보시면 됩니다.

이렇게 해서 안드로이드 로그인, 회원가입 구현에 관한 포스팅을 마치겠습니다.
회원정보에 관해 더 공부하여 추가적인 기능 구현하는 방법들을 가지고 오도록 하겠습니다. 감사합니다.