프로그래밍/안드로이드

[안드로이드] 쉐어드 프리퍼런스 저장/불러오기 (Shared Preference)

오치리일상 2017. 8. 13. 11:00

안드로이드의 앱에서 데이터를 저장하는 방법에 대해서 알아본다.

 

앱에서 데이터 저장은 sqlite(DataBase)를 이용하는 방법과 쉐어드 프리퍼런스(Shared Preference)를 이용하는 방법이 있다.

 

쉐어드 프레퍼런스는 sqlite(DataBase)를 사용하지 않아도 데이터 저장이 가능하다. 또 sqlite의 사용보다 좀 더 쉽게 사용할 수있다. 하지만 대용량의 데이터일 때 sqlite보다 느린 단점이 있다고 하니 간단한 환경변수 저장정도에 사용하면 좋을 듯 하다.

 

앱이 종료 후 다시 실행되도 저장한 데이터는 삭제되지 않으나 앱을 삭제시에는 데이터도 삭제된다.

 

 

아래 동영상에 프리퍼런스를 구현한 것을 코딩한 소스를 살펴본다.

 

 

 

* SharedPreference 정의

 

1. 저장

 

> SharedPreference 를 선언한다.

 

public final String PREFERENCE = "com.studio572.samplesharepreference";

SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);

// SharedPreferences 의 데이터를 저장/편집 하기위해 Editor 변수를 선언한다.
SharedPreferences.Editor editor = pref.edit();

// key값에 value값을 저장한다.
// String, boolean, int, float, long 값 모두 저장가능하다.
editor.putString(key, value);

// 메모리에 있는 데이터를 저장장치에 저장한다.
editor.commit();

 

SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);

첫번째 매개변수(PREFERENCE) : 저장/불러오기 하기 위한 key이다.

이 고유키로 앱의 할당된 저장소(data/data/[패키지 이름]/shared_prefs) 에 "com.studio572.samplesharepreference.xml" 로 저장된다.

이 때 xml 파일명은 사용자 정의가 가능하다.

 

> 두번째 매개변수(MODE_PRIVATE) : 프리퍼런스의 저장 모드를 정의한다.

 

[MODE_PRIVATE : 이 앱안에서 데이터 공유]

[MODE_WORLD_READABLE : 다른 앱과 데이터 읽기 공유]

[MODE_WORLD_WRITEABLE : 다른 앱과 데이터 쓰기 공유]

 

 

 

2. 불러오기

 

// SharedPreference 를 선언한다.
// 저장했을때와 같은 key로 xml에 접근한다.

SharedPreferences pref = getSharedPreferences(

PREFERENCE, MODE_PRIVATE

)

;

// key에 해당한 value를 불러온다.
// 두번째 매개변수는 , key에 해당하는 value값이 없을 때에는 이 값으로 대체한다.

String result = pref.getString(key

, ""

)

;

 

 

 

아래는 SharedPreference를 사용한 예제 소스.

 

특별한 코드는 없으니 한번 쓰윽 훑어보시면 될 듯 합니다.

 

위 유튜브 동영상의 구현 소스이다.

 

 

* MainActivity.java

package com.studio572.samplesharepreference;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

public final String PREFERENCE = "com.studio572.samplesharepreference";
public final String key01 = "key01";
public final String key02 = "key02";
public final String key03 = "key03";
public final String key04 = "key04";
public final String key05 = "key05";
private boolean isBoolean;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final TextView result = (TextView) findViewById(R.id.result);

final EditText inputString = (EditText) findViewById(R.id.edit01);
final Button inputBooleanTrue = (Button) findViewById(R.id.edit02_1);
final Button inputBooleanFalse = (Button) findViewById(R.id.edit02_2);
final EditText inputInt = (EditText) findViewById(R.id.edit03);
final EditText inputFlaot = (EditText) findViewById(R.id.edit04);
final EditText inputLong = (EditText) findViewById(R.id.edit05);

Button saveString = (Button) findViewById(R.id.save01);
Button saveBoolean = (Button) findViewById(R.id.save02);
Button saveInt = (Button) findViewById(R.id.save03);
Button saveFloat = (Button) findViewById(R.id.save04);
Button saveLong = (Button) findViewById(R.id.save05);

Button loadString = (Button) findViewById(R.id.load01);
Button loadBoolean = (Button) findViewById(R.id.load02);
Button loadInt = (Button) findViewById(R.id.load03);
Button loadFloat = (Button) findViewById(R.id.load04);
Button loadLong = (Button) findViewById(R.id.load05);

Button clear = (Button) findViewById(R.id.clear);

inputBooleanTrue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isBoolean = true;
}
});
inputBooleanFalse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isBoolean = false;
}
});

saveString.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setPreference(key01, inputString.getText().toString());
}
});
saveBoolean.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setPreference(key02, isBoolean);
}
});
saveInt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setPreference(key03, Integer.parseInt(inputInt.getText().toString()));
}
});
saveFloat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setPreference(key04, Float.parseFloat(inputFlaot.getText().toString()));
}
});
saveLong.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setPreference(key05, Long.parseLong(inputLong.getText().toString()));
}
});

loadString.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
result.setText("String: " + getPreferenceString(key01));
}
});
loadBoolean.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
result.setText("Boolean: " + getPreferenceBoolean(key02));
}
});
loadInt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
result.setText("Int: " + getPreferenceInt(key03));
}
});
loadFloat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
result.setText("Float: " + getPreferenceFloat(key04));
}
});
loadLong.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
result.setText("Long: " + getPreferenceLong(key05));
}
});

clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setPreferenceClear();
}
});
}
    

// 데이터 저장 함수
public void setPreference(String key, boolean value){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(key, value);
editor.commit();
}
public void setPreference(String key, String value){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, value);
editor.commit();
}
public void setPreference(String key, int value){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt(key, value);
editor.commit();
}
public void setPreference(String key, float value){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putFloat(key, value);
editor.commit();
}

public void setPreference(String key, long value){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putLong(key, value);
editor.commit();
}


// 데이터 불러오기 함수
public boolean getPreferenceBoolean(String key){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
return pref.getBoolean(key, false);
}
public String getPreferenceString(String key){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
return pref.getString(key, "");
}
public int getPreferenceInt(String key){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
return pref.getInt(key, 0);
}
public float getPreferenceFloat(String key){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
return pref.getFloat(key, 0f);
}
public long getPreferenceLong(String key){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
return pref.getLong(key, 0l);
}

// 데이터 한개씩 삭제하는 함수
public void setPreferenceRemove(String key){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.remove(key);
editor.commit();
}

 

// 모든 데이터 삭제
public void setPreferenceClear(){
SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
}

}

 

 

위 동영상에 나오는 UI대로 레이아웃을 코딩한다.

단순 레이아웃이므로 설명은 생략한다.,

 

* activity_main,xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal"
        android:background="#88ff0000">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:text="결과 : "
            android:textColor="#000000"/>
        <TextView
            android:id="@+id/result"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:gravity="center"
            android:text=""
            android:textColor="#000000"
            android:background="#88cccccc"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:text="입력변수 자료형"
            android:textColor="#000000"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="데이터 입력"
            android:textColor="#000000"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="저장"
            android:textColor="#000000"
            android:background="#cccccc"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="불러오기"
            android:textColor="#000000"
            android:background="#cccccc"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:text="String"
            android:textColor="#000000"/>
        <EditText
            android:id="@+id/edit01"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#000000"/>
        <Button
            android:id="@+id/save01"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="저장"
            android:textColor="#000000"
            android:background="#cccccc"/>
        <Button
            android:id="@+id/load01"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="불러오기"
            android:textColor="#000000"
            android:background="#cccccc"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:text="Boolean"
            android:textColor="#000000"/>
        <Button
            android:id="@+id/edit02_1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.2"
            android:text="ture"
            android:textColor="#000000"/>
        <Button
            android:id="@+id/edit02_2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.2"
            android:text="false"
            android:textColor="#000000"/>
        <Button
            android:id="@+id/save02"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="저장"
            android:textColor="#000000"
            android:background="#cccccc"/>
        <Button
            android:id="@+id/load02"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="불러오기"
            android:textColor="#000000"
            android:background="#cccccc"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:text="Int"
            android:textColor="#000000"/>
        <EditText
            android:id="@+id/edit03"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:layout_weight="1"
            android:textColor="#000000"/>
        <Button
            android:id="@+id/save03"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.2"
            android:text="저장"
            android:textColor="#000000"
            android:background="#cccccc"/>
        <Button
            android:id="@+id/load03"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="불러오기"
            android:textColor="#000000"
            android:background="#cccccc"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:text="Float"
            android:textColor="#000000"/>
        <EditText
            android:id="@+id/edit04"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:layout_weight="1"
            android:textColor="#000000"/>
        <Button
            android:id="@+id/save04"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="저장"
            android:textColor="#000000"
            android:background="#cccccc"/>
        <Button
            android:id="@+id/load04"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="불러오기"
            android:textColor="#000000"
            android:background="#cccccc"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:text="Long"
            android:textColor="#000000"/>
        <EditText
            android:id="@+id/edit05"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:layout_weight="1"
            android:textColor="#000000"/>
        <Button
            android:id="@+id/save05"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="저장"
            android:textColor="#000000"
            android:background="#cccccc"/>
        <Button
            android:id="@+id/load05"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:layout_weight="1.2"
            android:gravity="center"
            android:text="불러오기"
            android:textColor="#000000"
            android:background="#cccccc"/>
    </LinearLayout>
    <Button
        android:id="@+id/clear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="0"
        android:gravity="center"
        android:text="clear"
        android:textColor="#000000"
        android:background="#cccccc"/>

</LinearLayout>