© Khmer Angkor Academy - sophearithput168

Data Storage

រក្សាទុកទិន្នន័យ

Android ផ្តល់វិធីជាច្រើនក្នុងការរក្សាទុកទិន្នន័យ។ ការជ្រើសរើសវិធី storage ត្រឹមត្រូវគឺសំខាន់ណាស់!

🗄️ Storage Hierarchy (Decision Tree)

                    Need to store data?
                           │
        ┌──────────────────┼──────────────────┐
        ▼                  ▼                  ▼
   Simple data?      Structured data?    Large files?
   (key-value)         (tables)           (images)
        │                  │                  │
        ▼                  ▼                  ▼
 SharedPreferences    SQLite/Room      Internal/External
   DataStore                              Storage

📁 Storage Options Comparison

Type ពេលណាប្រើ Size Limit Speed
SharedPreferences Settings, preferences, flags < 1 MB ⚡⚡⚡ Very Fast
Internal Storage Private files, cache Available space ⚡⚡ Fast
External Storage Large files, shared files SD card size ⚡ Medium
SQLite Database Structured data, relationships ~2 GB ⚡⚡ Fast (indexed)
Room Database Modern SQLite wrapper ~2 GB ⚡⚡⚡ Fast + Safe

💾 SharedPreferences Deep Dive

SharedPreferences រក្សាទុកទិន្នន័យជា XML file នៅក្នុង /data/data/package_name/shared_prefs/

Feature Description
Storage Location Internal storage (private)
Data Format XML (key-value pairs)
Supported Types String, int, long, float, boolean, Set
Thread Safety ⚠️ Not thread-safe (use commit/apply correctly)
Performance Fast for small data (< 1MB)

🆕 DataStore (Modern Alternative)

DataStore គឺជា replacement ទំនើបសម្រាប់ SharedPreferences:

Feature SharedPreferences DataStore
Thread Safety ❌ Not safe ✅ Fully safe
Async/Await ❌ Blocking ✅ Coroutines/Flow
Type Safety ❌ Runtime errors ✅ Compile-time safety
Data Loss ⚠️ Possible (crashes) ✅ Transactional
Recommendation Legacy apps ✅ New projects

📂 Storage Locations

Location Path Access
Internal Storage /data/data/package_name/ 🔒 Private (app only)
External Storage /storage/emulated/0/ 🌐 Public (all apps)
Cache /data/data/package_name/cache/ 🗑️ Temporary (auto-delete)

🔐 Scoped Storage (Android 10+)

Android 10+ ដាក់ការកំណត់ access ទៅ external storage:

Before Android 10 Android 10+
✅ Direct file path access ❌ No direct access
❌ Security risks ✅ Use MediaStore API
❌ Permission required ✅ No permission for own files

💡 Best Practice: ប្រើ getFilesDir() for internal files និង MediaStore API សម្រាប់ shared files!

Java Code
Click "Run" to execute the Java code