Hot off the press - it was posted 3 minutes ago! The latest in the series : Developing for Android VI The Rules: Storage
tl;dr - Don't be lazy - It is easy while developing to start hard coding values for things such as file paths, or creating databases instead of tables in a database. Seriously, spend some time doing it right, your users and your app will thank you later!
- Avoid Hard-coded File paths - Just don't!
- Instead of /sdcard use APIs like Environment.getExternalStorageDirectory()
- Instead of trying to hardcode application path, use Context.getDatabasePath() or Context.getFilesDir()
- Persist Relative Paths Only - Backup/Restore as example
- Save the relative path only, as user may change device.
- Avoid heavy canonicalization except for security related reasons.
- Use Storage Cache for Temporary Files
- Files which can be cached, store them in Context.getCacheDir()
- Files in these folders can be deleted when space needs to be reclaimed by system.
- Files are never backed up in this folder, unlike data directory which are backed up
- Avoid SQLite for Simple Requirements
- Using SQLite for storing some key/value pairs does not make sense, use SharedPreferences - Read the article for important notes about Memory Leaks w/ Shared Prefs
- Use append-only log files, and rotate them periodically.
- Use LevelDB if all you need is NoSQL and are comfortable with JNI (this is new to me)
- Avoid Using Too many Databases
- Most applications should have at most, one database
- Besides, if you have one, then you can easily query across your tables.
- Let your user choose the content storage location
- Some devices have more than one storage location, utilize Storage Access Fragmework.
- Use intents w/ content:// URI to open / save files.
- DocumentFile support library helps you adapt existing code to traditional file-style API.
This post is really quite good as storage is kind of boring, you set it up, you use it, and cross your fingers that it works. This particluar post gives some good tips, and good methods to use to get the right directory for your project, it also made me aware of LevelDB - had not heard of it before. I was also made aware of the Storage Access Famework.. Most of the work I do though does not involve users saving / opening files to the file system, more database/shared preferences.. But it is always good to have this information around as reference material so you can pivot and use best practicies when you need them.
No comments:
Post a Comment