Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

기록장

[안드로이드] SharedPreferences / 데이터 저장, 복원 본문

안드로이드

[안드로이드] SharedPreferences / 데이터 저장, 복원

edit0 2021. 1. 1. 18:19

보통 데이터 저장이라 하면 DB나 서버에 데이터를 저장하고 가져와서 사용한다. 그러나 간단히 앱 내에서 데이터를 저장, 복구하고 싶을 때 사용할 수 있는 것이 SharedPreferences 객체이다.

 

SharedPreferences의 객체를 반환하는 3가지 메소드

 

- getPreferences(Context.MODE_PRIVATE): 별도 파일명을 지정하지 않고 액티비티 이름으로 저장된다. 하나의 액티비티만을 위한 저장 공간이 되며 다른 액티비티에서는 데이터를 이용할 수 없다.

- getSharedPreferences("파일명", Context.MODE_PRIVATE): 매개변수로 파일명을 주어 저장한다. 다른 액티비티나 컴포넌트들이 데이터를 공유해서 이용할 수 있다. 각각의 파일로 나누어 구분하여 저장하고자 할 때 주로 사용

- PreferenceManager.getDefaultSharedPreferences(this): 앱의 패키지명으로 저장한다. 파일명이 "패키지명_preferences"가 된다.

 

 

매개변수로 들어가는 모드 종류

 

- MODE_PRIVATE: 자기 앱 내에서 사용, 외부 앱에서 접근 불가

- MODE_WORLD_READABLE: 외부 앱에서 읽기 가능

- MODE_WORLD_WRITEABLE: 외부 앱에서 쓰기 가능

 

 

객체 사용 시 저장장소는 /data/data/패키지명/shared_pref/지정한 파일명 으로 찾을 수 있다.

(Device File Explorer에서..)

 

간략히 코드를 설명하자면..

앱이 종료되거나 다른 앱으로 넘어갈 경우에 데이터를 복원하기 위해 onPause() 메소드에 데이터를 저장하는 코드를 작성하였고 다시 앱을 켰을 때 데이터 복원을 위해 onResume() 메소드 내에 복원 코드를 작성하였다.

크게 어려운 점은 없을 것이다.

 

onPause(), onResume() 등 액티비티 생명주기에 대해 잘 모르겠다면 아래 링크 참고

https://edit0.tistory.com/8

Intent에 대해 잘 모르겠다면 아래 링크 참고

https://edit0.tistory.com/6

 

 

코드

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="아무거나 적어주세요"
        android:id="@+id/edittext1"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textview1"
        android:textSize="30dp"/>

</LinearLayout>

 

MainActivity.java

public class MainActivity extends AppCompatActivity {

    EditText et1;
    TextView tv1;

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

        android.util.Log.i("태그","onCreate()");

        setTitle("sharedPreferences");

        et1 = findViewById(R.id.edittext1);
        tv1 = findViewById(R.id.textview1);

    }

    @Override
    protected void onPause() {
        super.onPause();

        //getSharedPreferences 메소드를 참조 (저장될 파일명, 개인모드로 파일 생성)
        SharedPreferences sp = getSharedPreferences("shared",Activity.MODE_PRIVATE);
        //getPreferences(Context.MODE_PRIVATE);
        //PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sp.edit(); //edit 메소드 호출

        //저장할 값들 설정
        editor.putString("data1", et1.getText().toString());
        editor.putInt("data2",10);

        editor.commit(); //commit 메소드 꼭 호출, 안하면 저장이 안된다.
    }

    @Override
    protected void onResume() {
        super.onResume();

        //저장할 때와 마찬가지로 메소드 참조, 파일명은 불러올 파일 명으로..
        SharedPreferences sp = getSharedPreferences("shared", Activity.MODE_PRIVATE);
        //getPreferences(Context.MODE_PRIVATE);
        //PreferenceManager.getDefaultSharedPreferences(this);

        if(sp != null){
            String data1 = sp.getString("data1","No data");
            int data2 = sp.getInt("data2",0);
            tv1.setText(data1 +" / "+ data2);
        }
    }

}

 

결과

 

적어주고 종료

 

파일을 찾아가서 xml 파일을 열어보면 저장된 것을 볼 수 있다.

 

다시 앱을 실행하면 복원된 값을 볼 수 있다.

 

생성된 xml 파일들

 

 

부족한 점, 피드백 환영합니다.

 

감사합니다.