06 - Android Data Persistance
Main methods for data persistance
- Shared preferences
- Internal storage
- External storage
- SQLite Database
Saving data in between same Activity instances
Data forwarding actually!
- onSaveInstanceState
- onRestoreInstanceState
Shared preferences
SharedPreferences – save and retrieve key-value pairs
Any primitive data
- Booleans
- Floats
- Ints
- Longs
- Strings
To get a SharedPreferences object
getSharedPreferences(name, mode)– if you need multiple pref files, identified by name (first parameter)getPreferences(mode)– single pref file for activity, no name specified
Mode
- MODE_PRIVATE (0) - default
- MODE_WORLD_READABLE
- MODE_WORLD_WRITEABLE
To WRITE values
- Call
edit()to getSharedPreferences.Editor - Add values with
putString(),putBoolean, … - Commit values with
commit()
override fun onStop() {
super.onStop()
val sharedPref = getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putInt(getString(R.string.saved_high_score_key), newHighScore)
commit()
}
}
To READ values
Use methods such as getString, getBoolean
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// ?: - Elvis operator
val sharedPref = getPreferences(Context.MODE_PRIVATE) ?: return
val defaultValue = resources.getInteger(R.integer.saved_high_score_default_key)
val highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue)
}
Internal storage
- Private to application (default)
- No access for user or other apps
- When app gets uninstalled – files are deleted with it
Create/Write
Create and Write private file
- Call
openFileOutput(), with filename and operating mode - Returns
FileOutputStream - Write to the file with
write() - Close the file with
close()
Modes
- MODE_PRIVATE – create (or replace)
- MODE_APPEND
- MODE_WORLD_READABLE
- MODE_WORLD_WRITEABLE
Read
Read from private file
- Call
openFileInput()with filename - Returns FileInputStream
- Get bytes with
read() - Close stream with
close()
Static app files
Save static file during compile time
- Place in
/res/raw - Open with
OpenRawResource(), passingR.raw.<filename> - Returns inputStream
- File is read-only!!!
File cache
Caching data
- Do not need data forever
getCacheDir()- When space is low, Android will delete cache
- Stay within reasonable space limits (1mb?)
- Deleted with uninstall
- Manage cache files yourself
File methods
Other useful methods
getFilesDir()- Gets the absolute path to the filesystem directory where your internal files are saved.getDir()- Creates (or opens an existing) directory within your internal storage space.deleteFile()- Deletes a file saved on the internal storage.fileList()- Returns an array of files currently saved by your application.
External storage
All Android devices support shared "external storage"
Can be removable storage media (sd-card)
Or internal, non-removable storage
Files are world-readable
Access
Getting access – manifest
- READ_EXTERNAL_STORAGE
- WRITE_EXTERNAL_STORAGE
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
Availability
Check availability
- Use
getExternalStorageState()
Media might be mounted to a computer, missing, read-only, or in some other state.
// Checks if a volume containing external storage is available
// for read and write.
fun isExternalStorageWritable(): Boolean {
return Environment.getExternalStorageState() ==
Environment.MEDIA_MOUNTED
}
// Checks if a volume containing external storage is
// available to at least read.
fun isExternalStorageReadable(): Boolean {
return Environment.getExternalStorageState() in
setOf(Environment.MEDIA_MOUNTED,
Environment.MEDIA_MOUNTED_READ_ONLY)
}
Public files
- Files acquired through your app should be saved to a "public" location where other apps can access them and the user can easily copy them from the device
- Use one of the shared public directories (Music/, Pictures/, and Ringtones/)
- Use Enviroment.getExternalStoragePublicDirectory()
DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES
Private
- Private files (textures, sounds for app, etc) (actually semi-private)
- Use a private storage directory on the external storage
- Use getExternalFilesDir()
- Takes Type, use null when no type
- From 4.4 onwards does not require permissions
- Files are hidden from Media Scanner (but not from other apps with permissions)