오늘은 힘든 일요일이었으니 쉽고빠른 자동로그인을 해봅시다.

준비물은 로그인이 가능한 환경입니다...

서버와 로그인 api, 유저 데이터가 존재함을 바탕으로 SharedPreference 사용 방법만을 적었습니다.

java 언어를 기반으로 작성되었습니다.

 


0. SharedPreferences 간단 설명

 

안드로이드에서 사용 가능한 데이터베이스 관리 시스템(DBMS) 중 하나입니다. 

key - value 형태로 관리가 가능해서 간단한 데이터를 저장할 때 주로 쓰입니다. 전 자동로그인 할 때 가장 자주  사용하고 있습니다. 

 

더 자세한 내용을 알고싶다면 하단 링크를 참조해주세요.

 

https://developer.android.com/reference/android/content/SharedPreferences

 

SharedPreferences  |  Android Developers

 

developer.android.com

 

핵심 명령어

https://www.tutorialspoint.com/android/android_shared_preferences.htm

 

Android - Shared Preferences

Android - Shared Preferences Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preference

www.tutorialspoint.com

 

설명 및 사용예제

https://www.geeksforgeeks.org/shared-preferences-in-android-with-examples/

 

Shared Preferences in Android with Example - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

 

 


 

1. SharedPreferences를 위한 클래스 생성

 

SharedPreferences를 손쉽게 사용하도록 도와줄 클래스를 만들어줍니다.

public class SharedPreferencesManager {
    
}

 

그리고 SharedPreferences를 불러오기 위해 매번 사용해야하는 코드를 편리하게 사용할 수 있도록 메소드로 만들어줍니다.

 

private static final String PREFERENCES_NAME = "my_preferences";

public static SharedPreferences getPreferences(Context mContext){
    return mContext.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
}

 

왜 고작 한줄의 코드를 메소드로 빼두냐면, SharedPreferences는 불러오는 이름에 따라 저장할 수 있는 값이 달라집니다. 키 - 값 형태로 관리를 한다고 했으니, 다른 이름으로 getSharedPreferences 메소드를 사용하면 또 다른 값이 저장이 되겠죠?

따라서 저는 getPreferences라는 메소드로 자동로그인을 할 데이터만 저장할 예정이라 따로 만들었습니다. 

 

그리고 MODE_PRIVATE는 현재 사용하는 앱에서만 접근을 허락하도록 지정해놓은 것입니다. 여기에 관련된 자세한 항목은 상단 링크를 읽어보시면 더 자세히 알 수 있습니다.

 

이걸로 기본 준비는 끝났습니다.

 

 


 

2. 저장, 불러올 데이터 메소드 생성

 

로그인 정보를 저장, 불러오는 메소드를 만들어줍니다.

로그인의 가장 기본적인 데이터 email, password를 예시로 적었습니다.

필요한 정보를 저장해두면 됩니다!

 

public static void setLoginInfo(Context context, String email, String password){
    SharedPreferences prefs = getPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("email", email);
    editor.putString("password", password);

    editor.apply();
}

public static Map<String, String> getLoginInfo(Context context){
    SharedPreferences prefs = getPreferences(context);
    Map<String, String> LoginInfo = new HashMap<>();
    String email = prefs.getString("email", "");
    String password = prefs.getString("password", "");
        
    LoginInfo.put("email", email);
    LoginInfo.put("password", password);

    return LoginInfo;
}

 

해당 값이 null일 수 있으므로 defaultValue또한 공백문자로 처리했습니다. 이렇게 해두면 nullPointException 에러를 막을 수 있습니다. 

 

 


 

3. 사용과 활용

 

 

이제 SharedPreference를 어디서든 부를 수 있게 되었습니다.

따라서 사용자가 로그인 화면의 행동을 모두 끝마쳤을때.

즉, 유효한 데이터로 서버와 통신을 마치고 메인 화면으로 넘어갈 때

SharedPreferencesManager.setLoginInfo(this, email ,password);

이렇게 데이터를 저장해줍니다.

 

 

그 후, 한번 유효한 데이터로 로그인을 했던 사용자가 앱을 종료하고 다시 실행했을 때 SharedPreference에서 데이터를 가져옵시다.

Map<String, String> loginInfo = SharedPreferencesManager.getLoginInfo(this);
if (!loginInfo.isEmpty()){
    String email    = loginInfo.get("email");
    String password = loginInfo.get("password");
    }

 

이렇게 데이터를 가져오고 서버에 로그인 리퀘스트를 해주면 자동로그인이 완성됩니다.

만약 로그인 데이터가 잘못되었다면 로그인화면으로 넘겨야겠죠!

 

 

+ 이 외에도 아이디만 저장하기 기능도 SharedPreference를 활용할 수 있습니다. 보통 로그인 화면에서 체크박스로 확인하니, 로그인 할 때 해당 체크박스를 bool로 저장해두면 됩니다.

 


4. 삭제

 

가장 중요한부분!!!

바로 데이터 삭제입니다. 로그아웃을 했는데 다시 로그인이 되면 큰일나므로...

 

로그아웃, 회원탈퇴 시 꼭! 반드시!! sharedPreference를 삭제해야합니다.

삭제 코드는 다음과 같습니다.

 

public static void clearPreferences(Context context){
    SharedPreferences prefs = getPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.clear();
    editor.apply();
}

 

이제 로그아웃시 해당 메소드를 호출하면 됩니다.

 


 

SharedPreferences 전문입니다.

 

public class SharedPreferencesManager {

    private static final String PREFERENCES_NAME = "my_preferences";

    public static SharedPreferences getPreferences(Context mContext){
        return mContext.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
    }
    
    public static void clearPreferences(Context context){
        SharedPreferences prefs = getPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.apply();
    }

    public static void setLoginInfo(Context context, String email, String password){
        SharedPreferences prefs = getPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("email", email);
        editor.putString("password", password);

        editor.apply();
    }

    public static Map<String, String> getLoginInfo(Context context){
        SharedPreferences prefs = getPreferences(context);
        Map<String, String> LoginInfo = new HashMap<>();
        String email = prefs.getString("email", "");
        String password = prefs.getString("password", "");
        
        LoginInfo.put("email", email);
        LoginInfo.put("password", password);

        return LoginInfo;
    }
    
}

 

 

+ apply와 commit의 차이점!

commit()은 동기, apply()는 비동기 처리 됩니다.

+ Recent posts