티스토리 뷰
[Android studio] SharedPreferences를 이용한 데이터 저장하기 로컬 데이터 베이스
개발을 진행하다 보면 애플리케이션이 꺼졌다 켜져도 데이터가 유지되는 것을 원할 때가 있다.
DB를 사용하기에는 작은 규모의 데이터일 때 SharedPreferences를 이용하여 간단하게 사용할 수 있다.
우선 PreferenceManager.class를 생성하자
public class PreferenceManager {
public static final String PREFERENCES_NAME = "rebuild_preference";
private static final String DEFAULT_VALUE_STRING = "";
private static final boolean DEFAULT_VALUE_BOOLEAN = false;
private static final int DEFAULT_VALUE_INT = -1;
private static final long DEFAULT_VALUE_LONG = -1L;
private static final float DEFAULT_VALUE_FLOAT = -1F;
private static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
}
/**
* String 값 저장
* @param context
* @param key
* @param value
*/
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();
}
/**
* boolean 값 저장
* @param context
* @param key
* @param value
*/
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();
}
/**
* int 값 저장
* @param context
* @param key
* @param value
*/
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();
}
/**
* long 값 저장
* @param context
* @param key
* @param value
*/
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();
}
/**
* float 값 저장
* @param context
* @param key
* @param value
*/
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();
}
/**
* String 값 로드
* @param context
* @param key
* @return
*/
public static String getString(Context context, String key) {
SharedPreferences prefs = getPreferences(context);
String value = prefs.getString(key, DEFAULT_VALUE_STRING);
return value;
}
/**
* boolean 값 로드
* @param context
* @param key
* @return
*/
public static boolean getBoolean(Context context, String key) {
SharedPreferences prefs = getPreferences(context);
boolean value = prefs.getBoolean(key, DEFAULT_VALUE_BOOLEAN);
return value;
}
/**
* int 값 로드
* @param context
* @param key
* @return
*/
public static int getInt(Context context, String key) {
SharedPreferences prefs = getPreferences(context);
int value = prefs.getInt(key, DEFAULT_VALUE_INT);
return value;
}
/**
* long 값 로드
* @param context
* @param key
* @return
*/
public static long getLong(Context context, String key) {
SharedPreferences prefs = getPreferences(context);
long value = prefs.getLong(key, DEFAULT_VALUE_LONG);
return value;
}
/**
* float 값 로드
* @param context
* @param key
* @return
*/
public static float getFloat(Context context, String key) {
SharedPreferences prefs = getPreferences(context);
float value = prefs.getFloat(key, DEFAULT_VALUE_FLOAT);
return value;
}
/**
* 키 값 삭제
* @param context
* @param key
*/
public static void removeKey(Context context, String key) {
SharedPreferences prefs = getPreferences(context);
SharedPreferences.Editor edit = prefs.edit();
edit.remove(key);
edit.commit();
}
/**
* 모든 저장 데이터 삭제
* @param context
*/
public static void clear(Context context) {
SharedPreferences prefs = getPreferences(context);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
}
이제 본격적으로 데이터를 저장할 것인데 메인 액티비티에서 아래 코드를 입력해보자
PreferenceManager.setString(getApplicationContext(), "키값", "저장할 값");
필자는 우선 String형을 저장하는 예제를 작성했다.
키값과 저장할 값에 대해 이해하기 쉽게 예를 들어보겠다.
데이터를 사람이라고 생각해보자 그 사람의 이름은 김 OO이다
저기 멀리서 김 OO 씨 뛰어오세요!라고 하면 김 OO 씨의 몸이 뛰어오는 것이다.
여기서 김 OO 씨라는 이름은 키값 김 OO 씨의 뛰어오는 몸은 저장할 값이 되는 것이다.
저장한 데이터를 가져올 때는 김 OO 씨 이름만 알면 그 값을 가져올 수 있는 것이다.
아래와 같이 다시 작성해보자
//데이터 저장
String str = "나이 : 36세 성별 : 남자";
PreferenceManager.setString(getApplicationContext(), "kim",str);
//데이터 호출
String kim = PreferenceManager.getString(getApplicationContext(), "kim");
Toast.makeText(getApplicationContext(), kim, Toast.LENGTH_SHORT).show();
str 변수의 값을 "kim"이라는 키값으로 저장한 후 "kim"이라는 키값에 해당하는 값을 다시 호출했다.
다른 데이터 형식의 값도 저장할 수 있다.
주의할 점으로 SharedPreferences를 사용하면 스마트폰 로컬에 데이터가 남는다.
이 데이터를 열어볼 수 있으므로 보안에 취약하다.
유저의 개인정보와 같은 보안상 중요한 데이터는 SharedPreferences를 사용하여 저장하지 않도록 조심해야 한다.
'안드로이드 > JAVA' 카테고리의 다른 글
[Android Studio] 간단하게 캡처금지하기, 캡쳐방지 하기 (0) | 2020.10.31 |
---|---|
[Android Studio] 간단하게 버튼 중복클릭 시간 제한하기 (0) | 2020.10.30 |
[Android Studio] AsyncTask를 이용한 php+mysql HTTP POST 통신 (0) | 2020.10.28 |
[Android Studio] 안드로이드 스튜디오 타이틀 없애기, 액션바 없애기 (0) | 2020.10.27 |
[Android Studio] RecyclerView 리사이클러뷰 사용하기 리스트뷰 (0) | 2020.10.22 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- next.js ssr deploy
- next useEffect
- Android Studio
- 코틀린
- react native oss
- gitlab mirror
- kakao api notworking
- non-zero exit code detected
- github mirror
- rn 오픈소스 라이센스
- 라이브러리 라이센스
- 깃랩 잔디 옮기기
- 깃허브 잔디 옮기기
- 안드로이드 스튜디오 해시키
- react native 오픈소스 라이선스
- 카카오 해시키
- amplify build error
- amplify next.js
- rn oss
- react.js useEffect
- room error
- nextjs ssr deploy
- 깃랩에서 깃허브로
- next.js useEffect
- 안드로이드 스튜디오
- 커밋 이메일 변경
- Build failed because of webpack errors
- 안드로이드 해시키
- 깃허브에서 깃랩으로
- kotlin
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함