안드로이드 노트

[프로젝트1] 내가 로그인Activity를 구현한 방법

devRobin 2022. 3. 21. 10:18

전체 코드

더보기
package com.example.grapegraph;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    TextView createnewAccount;

    EditText inputEmail,inputPassword;
    Button btnLogin;
    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
    ProgressDialog progressDialog;

    FirebaseAuth mAuth;
    FirebaseUser mUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createnewAccount=findViewById(R.id.createNewAccount);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        inputEmail=findViewById(R.id.inputEmail);
        inputPassword=findViewById(R.id.inputPassword);
        btnLogin=findViewById(R.id.btnLogin);


        progressDialog=new ProgressDialog(this);
        mAuth=FirebaseAuth.getInstance();
        mUser=mAuth.getCurrentUser();

        createnewAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                startActivity(new Intent(MainActivity.this,RegisterActivity.class));
            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { perforLogin();}
        });



    }

    private void perforLogin() {
        String email = inputEmail.getText().toString();
        String password = inputPassword.getText().toString();



        if(!email.matches(emailPattern))
        {
            inputEmail.setError("Enter Correct Email");
            inputEmail.requestFocus();
        } else if(password.isEmpty() || password.length()<6)
        {
            inputPassword.setError("Enter Proper Password");
            inputPassword.requestFocus();
        }  else
        {
            progressDialog.setMessage("Please Wait While Login...");
            progressDialog.setTitle("Login");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();

            mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                     if (task.isSuccessful())
                     {

                         //if user is signing in first time then get and show user info from google account
                         if(task.getResult().getAdditionalUserInfo().isNewUser()){
                             FirebaseUser currentUser = mAuth.getCurrentUser();
                             //Get user email and uid from auth
                             String email= currentUser.getEmail();
                             String uid = currentUser.getUid();
                             //When user is registered store user info in firebase realtime database too
                             //Using HashMap
                             HashMap<Object,String> hashMap = new HashMap<>();
                             //put info in hashmap

                             hashMap.put("email",email);
                             hashMap.put("uid",uid);
                             hashMap.put("name",""); //will add later (e.g. edit profile)
                             hashMap.put("desc","");  //will add later (e.g. edit profile)
                             hashMap.put("image","");  //will add later (e.g. edit profile)

                             //firebase database isntance
                             FirebaseDatabase database = FirebaseDatabase.getInstance();
                             //path to store user data named "Users"
                             DatabaseReference reference = database.getReference("Users");
                             //put data within hashmap in database
                             reference.child(uid).setValue(hashMap);
                         }




                         progressDialog.dismiss();
                         sendUserToNextActivity();
                         Toast.makeText(MainActivity.this,"Login Successful",Toast.LENGTH_SHORT).show();
                     }
                     else
                     {
                         progressDialog.dismiss();
                         Toast.makeText(MainActivity.this,""+task.getException(),Toast.LENGTH_SHORT).show();
                     }
                }
            });




        }

    }

    private void sendUserToNextActivity() {
        Intent intent=new Intent(MainActivity.this,HomeActivity.class);
        intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}

 

 

상세 설명:

 

1. fullscreen을 위한 getWindow() 메소드

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

onCreate 안에 해준다.

 

2. emailPattern

1) emailPattern의 정규표현식을 다음과 같이 써준다.

 String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

영어 소문자, 대문자, 숫자 0~9, 특수문자 . _- + @ + 영어 소문자 + . + 영어 소문자

 

2) matches() 메소드 이용

matches(): 문자열에 정규표현식이 일치하는지를 boolean으로 리턴.

 private void perforLogin() {
        String email = inputEmail.getText().toString();
        String password = inputPassword.getText().toString();



        if(!email.matches(emailPattern))
        {
            inputEmail.setError("Enter Correct Email");
            inputEmail.requestFocus();
        } else if(password.isEmpty() || password.length()<6)
        {
            inputPassword.setError("Enter Proper Password");
            inputPassword.requestFocus();
        }  
        //생략

3. 로그인

 

1) FirebaseAuth, FirebaseUser 생성

FirebaseAuth mAuth;
FirebaseUser mUser;


//onCreate안에
mAuth=FirebaseAuth.getInstance();
mUser=mAuth.getCurrentUser();

2) mAuth.signInWithEmailAndPassword

mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                     if (task.isSuccessful())
                     {

                         //if user is signing in first time then get and show user info from google account
                         if(task.getResult().getAdditionalUserInfo().isNewUser()){
                             FirebaseUser currentUser = mAuth.getCurrentUser();
                             //Get user email and uid from auth
                             String email= currentUser.getEmail();
                             String uid = currentUser.getUid();
                             //When user is registered store user info in firebase realtime database too
                             //Using HashMap
                             HashMap<Object,String> hashMap = new HashMap<>();
                             //put info in hashmap

                             hashMap.put("email",email);
                             hashMap.put("uid",uid);
                             hashMap.put("name",""); //will add later (e.g. edit profile)
                             hashMap.put("desc","");  //will add later (e.g. edit profile)
                             hashMap.put("image","");  //will add later (e.g. edit profile)

                             //firebase database isntance
                             FirebaseDatabase database = FirebaseDatabase.getInstance();
                             //path to store user data named "Users"
                             DatabaseReference reference = database.getReference("Users");
                             //put data within hashmap in database
                             reference.child(uid).setValue(hashMap);
                         }

                         progressDialog.dismiss();
                         sendUserToNextActivity();
                         Toast.makeText(MainActivity.this,"Login Successful",Toast.LENGTH_SHORT).show();
                     }
                     else
                     {
                         progressDialog.dismiss();
                         Toast.makeText(MainActivity.this,""+task.getException(),Toast.LENGTH_SHORT).show();
                     }
                }
            });

 

3) sendUserToNextActivity()

 private void sendUserToNextActivity() {
        Intent intent=new Intent(MainActivity.this,HomeActivity.class);
        intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }