Shared Preferences - 임시로 저장시키거나 앱이 지워지기 전까지 데이터를 남겨 놓고 싶다 할 때 많이 사용하는 함수

 

설정 화면에서 많이 쓰임

 

앱을 삭제 할 시 모든 데이터가 사라짐

 

---------------------------------------------------

 

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">

    <EditText
        android:id="@+id/et_save"
        android:layout_width="100dp"
        android:layout_height="wrap_content" />

</LinearLayout>

---------------------------------------------------

 

 

MainActivity.java

package com.example.shared;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText et_save;
    String shared = "file";

    @Override
    protected void onCreate(Bundle savedInstanceState) { // 앱이 실행 될 부분
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_save = (EditText)findViewById(R.id.et_save);

        SharedPreferences sharedPreferences = getSharedPreferences(shared, 0);
        String value = sharedPreferences.getString("khon", "");
        et_save.setText(value);
    }

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

        SharedPreferences sharedPreferences = getSharedPreferences(shared, 0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String value = et_save.getText().toString();
        editor.putString("khon",value);
        editor.commit(); // 저장을 완료 하라는 뜻
    }
}

---------------------------------------------------

'안드로이드 앱 만들기' 카테고리의 다른 글

Navigation Menu 커스텀  (0) 2020.08.09
Web View  (0) 2020.08.06
Navigation Menu  (0) 2020.08.06
List View  (0) 2020.08.02
패키지구조 & 역할  (0) 2020.08.01
Posted by khon98
,