안드로이드 노트

[안드로이드][프로젝트1]SharedPreferences를 이용하여 인트로 화면에서 바로 홈으로 넘어가기

devRobin 2022. 3. 26. 15:35

 

 

기존 방식은 인트로 화면-> 웰컴 화면-> 로그인 화면 -> 홈 순으로 들어가는 방식이다.

그러나 나는 로그인 화면에서 아이디 저장에 체크가 되어 있다면 다음 앱 시작시,

인트로 화면 -> 홈 방식으로 들어가게 하고 싶었다.

 

내가 한 방법은 다음과 같다.

 

1. 레이아웃에 체크박스 추가하기.

            <CheckBox
                android:id="@+id/checkBox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="아이디 저장"
                android:fontFamily="@font/jua"
                android:textColor="@color/colorPrimaryDark"
                android:background="@color/colorPrimary"
            	//생략
                />

2. 로그인 화면 Activity에 다음과 같이 추가한다.

    CheckBox checkBox;
    SharedPreferences appData;

    private boolean saveLoginData;
    private String id;
    private String pwd;

3. onCreate에서 다음과 같이 추가한다.

        checkBox = findViewById(R.id.checkBox);

        //설정값 불러오기
        appData = getSharedPreferences("appData", MODE_PRIVATE);
        load();


        //이전에 로그인 정보를 저장시킨 기록이 있다면
        if(saveLoginData){
            inputEmail.setText(id);
            inputPassword.setText(pwd);
            checkBox.setChecked(saveLoginData);
        }

4. 다음과 같은 함수를 추가한다.

    //설정값을 저장하는 함수
    private void save(){
        //SharedPreferences 객체만으로 저장 불가능. Editor 사용
        SharedPreferences.Editor editor = appData.edit();

        //에디터객체 .put타입(저장시킬 이름, 저장시킬 값)
        //저장시킬 이름이 이미 존재하면 덮어씌움.

        editor.putBoolean("SAVE_LOGIN_DATA", checkBox.isChecked());
        editor.putString("ID", inputEmail.getText().toString().trim());
        editor.putString("PWD", inputPassword.getText().toString().trim());

        //apply, commit을 안 하면 변경된 내용이 저장되지 않음.
        editor.apply();
    }

    //설정값을 불러오는 함수
    private void load(){
        //SharedPreferences 객체 .get타입(저장된 이름, 기본값)
        //저장된 이름이 존재하지 않을 시 기본값
        saveLoginData = appData.getBoolean("SAVE_LOGIN_DATA", false);
        id = appData.getString("ID","");
        pwd = appData.getString("PWD", "");
    }

5. 이메일 ok, 비밀번호 ok시 firebase에서 정보를 찾기 전에 먼저 save()를 추가해준다.

 

이렇게만 하면 재시작을 하더라도 로그인 화면에서 저장한 아이디와 비밀번호가 뜬다.

그러나 내가 하고 싶은 것은 인트로화면에서 바로 홈 화면으로 가는 것이니 다음과 같은 작업을 해야한다.

 

내가 하고자하는 것은 로그인Activity에서 SharedPreferences를 이용하여 저장한 불리언, 아이디, 비밀번호 값을 IntroActivity에 불러와서 만약, 저장된 값이 있다면 IntroActivity에서 바로 로그인 작업을 하여 HomeActivity로 유저의 값을 넘기는 작업이다.

 

 

 

6. IntroActivity에서 다음과 같이 추가한다.

   SharedPreferences appData;
    private boolean saveLoginData;
    String id;
    String pwd;

    FirebaseAuth mAuth;

7. onCreate안에 다음과 같이 추가한다.

mAuth=FirebaseAuth.getInstance();

8. onCreate안에 다음과 같이 추가한다.

        Handler handler = new Handler();

        handler.postDelayed(new Runnable(){

            @Override
            public void run() {

                //설정값 불러오기
                appData = getSharedPreferences("appData", MODE_PRIVATE);
                id = appData.getString("ID","");
                pwd = appData.getString("PWD", "");
                saveLoginData = appData.getBoolean("SAVE_LOGIN_DATA", false);

                //이전에 로그인 정보를 저장시킨 기록이 있다면
                if(saveLoginData){
                    String email = id;
                    String password = pwd;

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

                                if (task.getResult().getAdditionalUserInfo().isNewUser()) {
                                    FirebaseUser currentUser = mAuth.getCurrentUser();
                                    String email = currentUser.getEmail();
                                    String uid = currentUser.getUid();

                                    HashMap<Object, String> hashMap = new 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)
                                    hashMap.put("ChartValues", "");

                                    FirebaseDatabase database = FirebaseDatabase.getInstance();
                                    DatabaseReference reference = database.getReference("Users");
                                    reference.child(uid).setValue(hashMap);

                                }
                                sendUserToNextActivity();
                            } else{

                            }
                        }
                    });
                } else{
                    Intent intent = new Intent (getApplicationContext(), WelcomeActiviity.class);
                    startActivity(intent); //인트로 실행 후 바로 WelcomeActivity로 넘어감.
                    finish();
                }
            }
            private void sendUserToNextActivity() {
                Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
                intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
            }

        },4000); //4초 후 인트로 실행

 

이렇게 해서 작업을 성공적으로 마쳤다.