บทนำ
ตัวอย่างนี้สาธิตการใช้ SharedPreferences เพื่อเก็บข้อมูลเล็กๆ น้อยๆ อย่างถาวร (Persistent) เช่น ชื่อผู้ใช้, รหัสผ่าน, ตั้งค่าแอป
ขั้นตอนที่ 1: สร้างโปรเจกต์
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="SharedPreferences Demo"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<EditText
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="75dp"
android:ems="10"
android:hint="Enter Name" />
<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/etName"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Enter Password"
android:inputType="textPassword" />
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/etPassword"
android:layout_alignStart="@id/etPassword"
android:layout_marginTop="10dp"
android:text="Login" />
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnLogin"
android:layout_alignStart="@id/btnLogin"
android:layout_marginTop="10dp"
android:text="Remember my credentials" />
</RelativeLayout>
ขั้นตอนที่ 3: MainActivity.kt
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var sharedPreferences: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
private lateinit var name: EditText
private lateinit var password: EditText
private lateinit var button: Button
private lateinit var checkBox: CheckBox
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "SharedPreferences Demo"
name = findViewById(R.id.etName)
password = findViewById(R.id.etPassword)
button = findViewById(R.id.btnLogin)
checkBox = findViewById(R.id.checkBox)
// ใช้ Default SharedPreferences
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
editor = sharedPreferences.edit()
// โหลดข้อมูลที่บันทึกไว้ (ถ้ามี)
checkSharedPreference()
button.setOnClickListener {
if (checkBox.isChecked) {
// บันทึกข้อมูล
editor.putString("checkbox", "true")
editor.putString("name", name.text.toString())
editor.putString("password", password.text.toString())
editor.apply() // Async, แนะนำสำหรับประสิทธิภาพ
} else {
// ล้างข้อมูล
editor.putString("checkbox", "false")
editor.putString("name", "")
editor.putString("password", "")
editor.apply()
}
}
}
private fun checkSharedPreference() {
val isChecked = sharedPreferences.getString("checkbox", "false") == "true"
name.setText(sharedPreferences.getString("name", ""))
password.setText(sharedPreferences.getString("password", ""))
checkBox.isChecked = isChecked
}
}
ขั้นตอนที่ 4: Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.sharedprefs">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
SharedPreferences แบบ Named (หลายไฟล์)
// สร้าง/เข้าถึงไฟล์เฉพาะ
val prefs = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE)
val editor = prefs.edit()
// โหมดอื่นๆ
// MODE_PRIVATE (default) - เข้าถึงได้เฉพาะแอปตัวนี้
// MODE_WORLD_READABLE - deprecated
// MODE_WORLD_WRITEABLE - deprecated
Data Types ที่รองรับ
| Method | ประเภทข้อมูล |
|---|---|
| putString / getString | String |
| putInt / getInt | Int |
| putBoolean / getBoolean | Boolean |
| putFloat / getFloat | Float |
| putLong / getLong | Long |
| putStringSet / getStringSet | Set<String> |
apply() vs commit()
- apply() - Asynchronous, ไม่คืนค่า, ใช้ใน UI Thread ได้
- commit() - Synchronous, คืนค่า Boolean (สำเร็จ/ล้มเหลว), ใช้ใน Background Thread
หมายเหตุ: DataStore (Modern Replacement)
Android แนะนำให้ใช้ DataStore (Preferences DataStore / Proto DataStore) แทน SharedPreferences สำหรับโปรเจกต์ใหม่ เนื่องจาก:
- ใช้ Coroutines และ Flow
- Type-safe
- จัดการ Migration ได้ดีกว่า
- ไม่บล็อก Main Thread