티스토리 뷰


* 이번에는 자동 로그인 등과 같은 기능을 구현할 때 유용하게 사용할 수 있는 기능인 SharedPreference에 대하여 알아보도록 하자.


- 이전 글

2012/11/07 - [Android(안드로이드) 앱 개발 기초] 안드로이드 프로젝트 생성하고 에뮬레이터로 앱 실행하기

2012/11/10 - [Android(안드로이드) 앱 개발 기초] 간단한 인터페이스 구현과 다른 Activity로 넘어가기

2012/11/21 - [Android(안드로이드) 앱 개발 기초] Activity 라이프사이클 공부

2012/11/24 - [Android(안드로이드) 앱 개발 응용] Google Map API로 지도 보여주기(MapView), Overlay Item 그려주기 예제

2012/11/28 - [Android(안드로이드) 앱 개발 응용] Location GPS 위치 가져오기 및 최적화

2012/12/05 - [Android(안드로이드) 앱 개발 기초] 런타임 설정(로테이션, orientation) 변환 라이프사이클

2012/12/19 - [Android(안드로이드) 앱 개발 응용] 쉽게 Google Map 위에 말풍선 띄우기

2013/03/03 - [Android(안드로이드) 앱 개발 기초] Fragment 기초

2014/09/24 - [Android(안드로이드) 앱 개발 기초] ContentProvider 앱 간 데이터 공유 기본



* Key-Value 저장하기

: 만약 키-값의 조합이 많지 않고 적다면 SharedPreference API를 사용하는 것이 좋다. SharedPreferences 객체는 키-값 조합을 가지는 파일을 가리키며, 간단한 방법으로 이를 읽고 쓸 수 있도록 해주고 있다. 각 SharedPreferences 파일은 프레임워크에서 관리되고 있으며, 이들이 공유되거나 private으로 만들수도 있다.


* 참고: SharedPreferences API는 키-값 조합을 단순히 쓰고 읽는 API에 해당되며, 사용자의 UI를 설정하거나 앱의 세팅을 설정하는 Preference API와 혼동해서는 안된다. Preference API는 내부적으로 SharedPreferences API를 쓰기는 하지만, 별도로 구분하여 사용하면 좋다.



* SharedPreferences 핸들 가져오기

: 아래의 몇 함수를 호출함으로써 SharedPreference의 새로운 파일을 생성할수도 있고, 기존에 있었던 파일을 다시 불러오는 것도 가능하다.


  • getSharedPreferences(): 여러 개의 shared preferences 파일이 필요하다면 이름으로 구분하여 가져올 때 사용한다. 앱 내부의 어느 Context에서든지 호출이 가능하다.
  • getPreferences(): 하나의 shared preference 파일을 사용한다면 Activity에서 호출하여 해당하는 파일을 가져올 수 있다. 이 때에는 Activity에 기본적으로 할당된 shared preference를 가져오므로 이름을 별도로 제공하지 않아도 된다.

: 예를 들면, 아래의 코드는 Fragment 안에서 실행될 수 있다. 이 때에 첫 번째 인자로 넘기는 문자열에 해당하는 shared preferences 파일에 접근하여 private 모드로 접근을 허용하게 된다.

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
        getString(R.string.preference_file_key), Context.MODE_PRIVATE);

: SharedPreferences 파일에 이름을 부여할 때에는 앱에서 유니크한 키 값을 설정하여 할당해줘야 한다. 아니면 만약 하나의 Activity에 하나의 shared preference 파일이 필요하다면 파일명 파라미터 없이 getPreference() 함수를 호출하면 된다.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

* 주의: 만약 MODE_WORLD_READABLE이나 MODE_WORLD_WRITEABLE을 파라미터로 넘겨주게 된다면 다른 앱에서 파일명을 안다면 해당하는 데이터에 접근이 가능하게 된다.



* SharedPreferences에 값 쓰기

: SharedPreferences 파일을 쓰기 위해서는, edit()함수를 호출함으로써 SharedPreference.Editor를 생성해야 한다. 그리고 putInt()함수나 putString() 함수를 호출하여 키와 값을 넘겨주고 마지막에 commit() 함수를 호출하게 되면 변경된 내용들을 저장하게 된다. 아래가 예이다.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();


* SharedPreferences에서 값 읽기

: SharedPreferences 파일에서 값을 가져오기 위해서는 getInt()나 getString()과 같은 함수를 호출하여 가져올 수 있다. 키를 함수의 파라미터로 넘겨줌으로써 그에 해당하는 값을 가져올 수 있다. 만약 값이 존재하지 않는다면, 기본 값을 리턴하게 된다. 아래가 그 예이다.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);




* 자동 로그인 기능 구현 방안

: 위의 SharedPreference를 통해서 자동 로그인 구현 방안을 생각해보면 아래와 같이 할 수 있다. 

public class LoginSharedPreference {
    public static void setLogin(Activity ctx, String userName) {
        Editor editor = ctx.getPreferences(Context.MODE_PRIVATE).edit();
        editor.putString(R.string.user_name, userName);
        editor.commit();
    }

    public static void logout(Activity ctx) {
        Editor editor = ctx.getPreferences(Context.MODE_PRIVATE).edit();
        editor.putString(R.string.user_name, "");
        editor.commit();
    }

    public static void isLogin(Activity ctx) {
        return ctx.getPreferences(Context.MODE_PRIVATE).getString(R.string.user_name, "") != "";
    }
}

: 로그인하게 되면 setLogin을 호출하고, 로그아웃을 하게 되면 logout함수를 호출, 그리고 자동 로그인 여부를 체크하기 위해서는 isLogin 함수를 호출하면 된다. 위의 함수들을 Activity 안에다가 넣을수도 있고, 별도의 클래스로 활용해도 될 것이다.


끝.



Portions of this page are reproduced from work created and shared by the Android Open Source Project and used according to terms described in theCreative Commons 2.5 Attribution License.

참고http://developer.android.com/training/basics/data-storage/shared-preferences.html



공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함