본문 바로가기
Programming/Android

[Android] SharedPreferences 내 입맛대로 사용하기.

by 코딩의성지 2019. 10. 20.

요즘 너무 바빴다. 너무 바쁘게 지냈다는 핑계를 대면서 오랜만에 포스팅을 한다.

 

아주 오래전 글에 요즘 안드로이드 프로젝트를 진행하고 있다는 얘기를 한 적 있다. 

 

개발을 하다보면 서버와의 통신을 통해 DB에서 데이터를 가져와야하는 일이 많은데, 간단한 설정 값 같은 건 매번 DB를 통해 호출하다 보면 앱의 성능이 굉장히 떨어진다. 이럴 때 사용하라고 안드로이드에서는 기본적으로 SharedPreferences라는 녀석을 제공한다.

 

그렇다면 SharedPreferences 란 무엇일까?

SharedPreferences는 액티비티나 어플리케이션의 설정값이나 UI 정보 같은 간단한 정보 값을 XML (Key, Value) 기반의  파일형태로 저장하고 꺼내쓸 수 있는 것이다. 저장되는 데이터는 data/data/패키지명/shared_prefs/ 에서 확인할 수 있다.

 

안드로이드가 모바일 디바이스에 올라와 있는 OS이다 보니, 만약 앱을 사용하다가 메모리가 부족할 경우 메모리에 올라와 있는 앱들이 그냥 종료될 가능성도 있다. SharedPreferences는 이런 경우를 대비하기에 좋다. 그리고 또한 자동로그인이나 로그인 세션 유지가 같은 경우에도 이 SharedPreferences를 사용할 수 있다.

 

SharedPerferences를 그냥 쓰지말고 나처럼 Customizing 에서 사용하는 것도 좋은 방법이다.

아래의 소스는 Custom하게 작성한 예제 소스이다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package solo.shinhan.com.solo.data;
 
import android.content.Context;
import android.content.SharedPreferences;
 
public class CustomPreferences {
    public static final String PREFERENCES_NAME = "custom_preferences";
 
    private static final String DEFAULT_STRING_VALUE = "";
    private static final int DEFAULT_INT_VALUE = -1;
    private static final long DEFAULT_LONG_VALUE = -1l;
    private static final float DEFAULT_FLOAT_VALUE = -1.0f;
    private static final boolean DEFAULT_BOOLEAN_VALUE = false;
 
    private static SharedPreferences getPreferences(Context context) {
        return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
    }
 
    public static void setString(Context context, String key, String value) {
        SharedPreferences prefs = getPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key, value);
        editor.commit();
    }
 
    public static void setInt(Context context, String key, int value) {
        SharedPreferences prefs = getPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(key, value);
        editor.commit();
    }
 
    public static void setLong(Context context, String key, long value) {
        SharedPreferences prefs = getPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putLong(key, value);
        editor.commit();
    }
 
    public static void setFloat(Context context, String key, float value) {
        SharedPreferences prefs = getPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putFloat(key, value);
        editor.commit();
    }
 
    public static void setBoolean(Context context, String key, boolean value) {
        SharedPreferences prefs = getPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }
 
    public static String getString(Context context, String key) {
        SharedPreferences prefs = getPreferences(context);
        String value = prefs.getString(key, DEFAULT_STRING_VALUE);
        return value;
    }
 
    public static int getInt(Context context, String key) {
        SharedPreferences prefs = getPreferences(context);
        int value = prefs.getInt(key, DEFAULT_INT_VALUE);
        return value;
    }
 
    public static long getLong(Context context, String key) {
        SharedPreferences prefs = getPreferences(context);
        long value = prefs.getLong(key, DEFAULT_LONG_VALUE);
        return value;
    }
 
    public static float getFloat(Context context, String key) {
        SharedPreferences prefs = getPreferences(context);
        float value = prefs.getFloat(key, DEFAULT_FLOAT_VALUE);
        return value;
    }
 
    public static boolean getBoolean(Context context, String key) {
        SharedPreferences prefs = getPreferences(context);
        boolean value = prefs.getBoolean(key, DEFAULT_BOOLEAN_VALUE);
        return value;
    }
 
    public static void remove(Context context, String key) {
        SharedPreferences prefs = getPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.remove(key);
        editor.commit();
    }
 
    public static void clear(Context context) {
        SharedPreferences prefs = getPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.commit();
    }
}
 
 

간단하게 코드 설명을 하겠다. 코드를 보면 알겠지만 SharedPreferences 와 SharedPreferences.Editor를 주로 쓰는 걸 알 수 있다.

 

1
2
3
    private static SharedPreferences getPreferences(Context context) {
        return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
   }
 

이 메서드를 통해 데이터를 저장하거나 읽어올 XML 파일 정보를 가져오는데, 여기서 첫번째 파라미터는 XML 파일 이름을 뜻하고, 두번째 파라미터는 접근 권한을 의미한다. 접근 권한에 대해 자세하게 설명해보자면 아래와 같다.

  • MODE_PRIVATE : 해당 앱에서만 읽기, 쓰기 가능
  • MODE_WORLD_READABLE : 다른 앱에서 읽기 가능
  • MODE_WORLD_WRITEABLE : 다른 앱에서 쓰기 가능
  • MODE_MULTI_PROCESS : 다른 앱에서 읽기와 쓰기 가능

그리고 put을 통해서 데이터를 넣고 get을 통해서 데이터를 꺼내서 쓰면된다.

 

 

그리고 각 메서드 바디를 자세하게 보면 commit() 을 날리는 것을 볼 수 있다. 이는 xml 파일을 변경한 걸 저장하는 거라고 생각하면 된다. 안해주면 변경이 안되니 꼭 해주길 바란다.

 

오늘 글은 이정도 쓰도록 하겠다. 다들 오늘도 즐거운 코딩하자.

반응형

댓글