홍드로이드의 야매코딩

#8 안드로이드 스튜디오 데이터 저장 ( Shared Preferences ) 예제 [ 홍드로이드 ] 본문

Android Java

#8 안드로이드 스튜디오 데이터 저장 ( Shared Preferences ) 예제 [ 홍드로이드 ]

홍드로이드 2019. 5. 21. 01:29





[activity_main.xml]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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>
cs




[MainActivity.java]

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
32
33
34
35
36
37
package com.example.sharedexample;
 
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
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("hong""");
        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("hong", value);
        editor.commit();
 
    }
}
 
cs


Comments