본문 바로가기
안드로이드 자바

[JAVA][Android] SharedPreferences 데이터 저장 및 불러오기

by teamnova 2021. 8. 28.

SharedPreferences란?

- 간단한 값 저장에 DB를 사용하기에는 복잡하기 때문에 SharedPreferences를 사용하면 적합하다.

- 보통 초기 설정값이나 자동로그인 여부 등 간단한 값을 저장하기 위해 사용한다.

- 어플리케이션에 파일 형태로 데이터를 저장한다.

=> data/data/패키지명/shared_prefs/SharedPreference이름.xml 위치에 저장

- 어플리케이션이 삭제되기 전까지 보존된다.

 

1.MainActivity

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button btnStart, btnEnd;
    private EditText edit_text;
    private Context context;
    private TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart = (Button)findViewById(R.id.btn_start);
        btnEnd = (Button)findViewById(R.id.btn_end);
        edit_text = (EditText)findViewById(R.id.edit_text);
        result = (TextView)findViewById(R.id.result);
        context = this;
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setString(context,"savedata",edit_text.getText().toString());
                Toast.makeText(context,"저장되었습니다.",Toast.LENGTH_SHORT);
            }
        });

        btnEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result.setText(getString(context,"savedata"));


            }
        });


    }
    private static SharedPreferences getPreferences(Context context) {

        return context.getSharedPreferences("data", Context.MODE_PRIVATE);

    }
    private void setString(Context context, String key, String value) {

        SharedPreferences prefs = getPreferences(context);

        SharedPreferences.Editor editor = prefs.edit();

        editor.putString(key, value);

        editor.commit();

    }

    private String getString(Context context, String key) {

        SharedPreferences prefs = getPreferences(context);

        String value = prefs.getString(key, "기본값");

        return value;

    }


}

2.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:orientation="vertical">
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"></EditText>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="저장된 글 : "></TextView>
    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></TextView>
    </LinearLayout>


    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Shared 저장"
      />
    <Button
        android:id="@+id/btn_end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Shared 가져오기"
        />
</LinearLayout>