๐Ÿ“˜ Programming/Android

#8 SharedPreference(์‰์–ด๋“œ ํ”„๋ฆฌํผ๋Ÿฐ์Šค)

ํ•œ์ฝ”๋”ฉ 2020. 5. 5. 15:38
728x90
728x90
<?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="match_parent"
        android:layout_height="wrap_content"
        android:hint="์ž…๋ ฅ"
        android:textSize="30dp"
        />

</LinearLayout>
package com.example.sharedexample;

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 = findViewById(R.id.et_save);

        SharedPreferences sharedPreferences = getSharedPreferences(shared, 0);
        // ๊บผ๋‚ด์˜ค๋Š” ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— ๋นˆ ๊ฐ’ ๋„ฃ์Œ
        String value = sharedPreferences.getString("han","");
        et_save.setText(value);
    }

    // Ctrl + 'O'
    @Override
    protected void onDestroy() {
        super.onDestroy();

        // ์‰์–ด๋“œ ํ”„๋ฆฌํผ๋Ÿฐ์Šค์™€ ์—๋””ํ„ฐ๋ฅผ ์—ฐ๊ฒฐํ•ด์คŒ
        SharedPreferences sharedPreferences = getSharedPreferences(shared, 0);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        String value = et_save.getText().toString();

        // han์ด๋ผ๋Š” ๋ณ„๋ช…์„ ๊ฐ€์ง„ ์‰์–ด๋“œ ํ”„๋ฆฌํผ๋Ÿฐ์Šค ๊ฐ’ value๋ฅผ ์ €์žฅ
        editor.putString("han", value);
        editor.commit();    // ์—๋””ํ„ฐ์— ์ ์šฉ ์™„๋ฃŒ
    }
}

 

6.41๋ถ„์— ์ž…๋ ฅํ•˜๊ณ  6:42๋ถ„์— ๋‹ค์‹œ ์•ฑ ๋“ค์–ด๊ฐ€์„œ ๋ณด๋‹ˆ ๊ทธ๋Œ€๋กœ ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ

728x90
๋ฐ˜์‘ํ˜•