Jump to Section
Introduction
Locally or distantly, every mobile application needs storage of user data in one form or another. This data can be of different formats: Key-value pairs(user-name and password), User settings, Application settings, Texts, Spreadsheets, Numbers, Presentations, Images, Audio or Videos.
Moreover, things vary when it comes to accessibility of data of the application. In time you need to privately store some data. At the same time, some data should be stored for the user access. Evenly sometimes the data of your app needs to be accessed by other applications or you may access the data of other applications.
Thanks to android for providing a number of solutions to deal with data storage. The solution you choose depends on your precise demands, such as the size of data, type of data and accessibility of data.
Before we start discussing the top 10 ways of storing data in Android, lets first have an understanding of two basic techniques to store data i.e Local Storage and Distant Storage which further include various methods.
- Local Storage – Locally stored data is within the application scope or on the device storage. However, in both the terms, data is at all times present in the device and you can access it whenever needed.
- Distant Storage – Distantly stored data is present in the cloud or other online server and you shall need an Internet connection to retrieve data when needed.
This article will introduce you to the top 10 different storage options available on Android to save data locally and distantly.
1. Saved Instance State
Yes! Saved Instance state is the very first scene when you are storing and retrieving the data in your application. For newbies in Android programming let me explain what saved instance do.
According to the Activity lifecycle, when the application goes to background or if the configuration of the device is changed, then the activity is destroyed and created again. So the activity goes through the same process again of creating objects, fetching data, displaying UI and blah blah…
Think of an example that you are using a chat application. With a lot of efforts, you wrote a huge paragraph filled with emotions and feelings. Before sending the message you accidentally pressed back/home button or device configuration is changed. And when you come back again to the chat window every single word is gone. How bad will you feel at the moment? Probably you’ll throw out the application from your device.
Here Android introduce you to the concept of saved instance state. onSaveInstaceState() method is called when an activity is destroyed which takes a Bundle as a parameter. This bundle is a collection of a key-value pair in which we can store the state of every view in the bundle let it be Edittext, TextView, CheckBox or the scrolled position of list view or recycler view.
When the application is restarted then onRestoreInstanceState() is called to which we provide this bundle and it automatically restores the activity to the state in which it was closed. This agenda enhances the user experience and increases the probability of your app to remain installed on the user’s device.
what to save?
As a best practice, you should store the following in saved instance state:
- texts in edit texts
- instances of ImageViews
- the position of scroll views
- the current playback time of videos
- checks of checkboxes
- currently selected view
what not to save?
- Images
- videos
- files
- Internet downloads
- models or POJO
Advantages of saved instance state
- State of the activity is restored the if the activity is closed.
- saving data is quick and simple in key-value pairs.
- useful when device orientation is changed.
Disadvantages if saved instance state
- Data stored is not persistent i.e; data is lost if the device is restarted.
- Do not save data if the app is closed via finish() method.
2. SHARED PREFERENCES
Shared preferences provide a quick interface to save and retrieve small unstructured data in a key-value pair. You have a string key, and the corresponding primitive value for that key: boolean, String, int, float or long. The data in shared preferences persist across user session even if your application is killed and restarted or the device is rebooted.
Android platform stores the applications shared preferences in an XML file with private access to the application. An application may have one(default shared preference of application) or more Shared preference files(defined with unique names).
Shared preference data is lost when the user uninstalls the application or clears the application data from settings.
what to save?
To point out what kind of data to store in shared preference consider the example of a game application. Every time the user logs in to the application user should be able to see the username, the last level he was in coupled with the high score that user has made. Also, the application has to maintain user settings preferences, if the user has turned on/off the music of the game or notifications.
what not to save?
At the same time, there are things that shared preferences are not capable of storing. When it comes to storing of large data then shared preference is not the right choice. It fails to store large data. Do not opt for shared preferences when you need to store Images, videos, Audio files, large text files, spreadsheets or presentations.
Advantages of Shared Preferences
- works on the key-value basis. Simply provide the key and get corresponding value.
- Just a few lines of code required manipulated to manipulate data.
- data is private to your application
- useful when needing to stored user preferences.
- when needed, you can share data among applications.
- Reading and writing data is easy and fast
- Unless the application is uninstalled or data is cleared from settings, data persists in the application.
Disadvantages of Shared Preferences
- Cannot store a large amount of data.
- Cannot store Image, Audio or video data.
- Fails to store structured data.
- Storing huge amount of data in memory affects the speed and efficiency of the application.
3. Internal File storage
There are several situations when you need to persist data but shared preference does not meet your needs i.e; the data is larger in amount or the data type is not primitive. In this case, we store the data in device storage.
Every Android device’s file storage area is divided into two parts: Internal storage and External storage.
Internal storage is a built-in-non-volatile memory which is always available on the device. The internal storage directory is private to your application and the data cannot be accessed by other applications. Moreover, you may store text and binary data like images in your device’s internal memory. The data saved in the internal storage of the device is removed as soon as the application is uninstalled from the device.
File class and its various methods are used to store and retrieve the data in internal file storage.
what to save?
you should store the following types of data in internal storage:
- large text files
- spreadsheets or CSV files
- Image thumbnails
What not to save?
- Large audio files
- video files
- files larger than total 1mb.
Advantages of internal file storage
- Data access is private
- neither the user nor other applications can access the data in internal storage.
- Internal storage is always available on the device.
- Read and write data do not require user permissions.
Disadvantages of internal file storage
- Uninstalling the application removes data internal storage.
- cannot store a large amount of data.
4. Internal cache files
There may be conditions when you want to keep the files temporarily rather than persisting the data in the storage. In this case, you must use the cache directory to save the data. Every application has private cache directory that may be used to store and retrieve temporary data. Cache files are deleted by Android OS automatically whenever your device runs low on storage without any warning. Hence, you need to take care of this while reading files from cache.
what to save?
- Image thumbnails
- video thumbnails
- URLs
what not to save?
- Any sort of data that you need to persist for a long time.
- the large size of data.
Advantages of Internal cache files
- Always available on the device
- data processing is faster
Disadvantages of Internal cache files
- Deletes data when the device is low on memory without any warning.
- cannot store a large amount of data.
5. External file storage
External storage is a removable storage medium like an SD Card. Today a lot of devices do not support SD card. However, the permanent storage is divided into internal and external storage modules. You will need user permissions to access(read and write) external storage.
The external storage is however by default public in access. Any application or user can see and manipulate the data in external storage.
File class and its methods to save, retrieve and delete the data in external file storage. It stores a large amount of data with any data type.
what to save?
- Large size images
- Audio and video files
- downloads from the internet
- Document files
what not to save?
- Any data that you do not want to share with other applications or the user.
Advantages of external file storage
- Store huge amount of data.
- can store any type of data.
- data remains in the storage even if the application is uninstalled or data is cleared from settings.
Disadvantages of external file storage
- Data is world readable. In general, any application or user can read the data.
- Not always available as the user may remove the SD card from the device.
6. SQLite Database
At the present time, most of the mobile applications are simply clients that communicate with a server to collect and transmit data in real-time. Without an active Internet connection, these applications are worthless. If the user opens your app and sees nothing in it then what is the purpose of keeping it installed on the device.
Furthermore, there are applications that work offline and store all the user data locally. Then, the challenge arises to manage the user’s data. In addition, the user’s data must be private to your app. Lastly, Uninstalling the application must erase the user’s data.
For this purpose, we have the concept of SQLite database which can efficiently manage user’s data.
SQLite is an RDBMS library that implements SQL database engine which is:
- self-contained (no other component required)
- serverless (no server backend)
- zero-configuration (does not need to configure)
- transactional (changes within a single transaction in SQLite)
- stores data in a table of rows and columns.
Transactions in SQLite are ACID and the system crashes do not affect them. SQLite database is a premium choice when you need to manipulate structured data frequently.
Query
We use a query language to interact with the database. Queries can be complex but basically, we use the following operations:
- inserting data
- deleting data
- updating data
- retrieving data
You’ll learn the query structure as we proceed with the developing of application.
Cursors
A Cursor is an object interface that provides random read-write access to the result set returned by the database query. In other words, A cursor is a pointer to the rows of the table of the database. A cursor class provides methods to run the cursor throughout the structured data, and methods to retrieve data from columns of each row. Then you have to iterate the result to do something with data.
what to save?
- Related data like a phone contact
- user statistics
- update, delete and view flags.
- URLs and URI
what not to save?
- Images as well as media files
- non-relational data
- single key-value pair
- Document files
Advantages of SQLite database
- Serverless hence, no configuration required
- able to control redundancy of data
- maintains the integrity of stored information
- can share data using content providers when needed
- integrated with Android studio
Disadvantages of SQLite database
- Cannot store media files
- data loss on removal of the application
7. Realm Database
The Realm is an open source, object-oriented mobile database. A complete alternative to SQLite database. Like SQLite DB, The Realm Database is lightweight and highly performant, capable of handling very large data loads and running queries in fractions of a second. Based on shared live objects, it syncs data seamlessly in real-time with the Realm Object Server without the need to write networking, serialization, or object-relational mapping code. This means that your app will be able to refresh data as fast as needed to provide an enjoyable, engaging user experience.
Realm DB is faster than SQLite and also you need to write less code to manipulate data than the later. Realm also has cloud server for synchronizing data on all the user’s devices.
Advantages of Realm Database
- Fast and efficient
- require less code
- data can be sync on all devices of the same user
Disadvantages of Realm Database
- Needs configuration in the Android studio before use.
8. Network connection
The network connection can be used to retrieve and send data to a back-end server of your application. In this case, backend server maintains the database of your application. There are several APIs through which you can access this data. Every time you have to hit an API URL to receive or send data.
Usually, the data is received in JSON or XML format using RESTful or SOAP API’s and you store this JSON data in model class of your application. Then the data in Model class represents data.
To perform network operations we have the following packages that we can use:
- java.net.*
- android.net.*
Every time to perform a network operation you have to open an HTTP connection and provide the method as GET or POST. After that, you may be able to connect to the API URL and exchange the data.
For using the network connection you have to be careful that your device has a working internet connection. Also at runtime, you have to check the permissions to reduce the chances of crashing your application.
what to save?
- Media files
- Documents
- User preferences
what not to save?
- Application settings
- Any data that you may need offline
Advantages of Network connection
- Even uninstalling the application do not affect the data.
- Can store any amount of data
Disadvantages of network connection
- Internet connection is must to transfer data.
- If backend server crashes then all the data may lose.
9. Backing up Application data
Alright, Now comes the most important storage option in android. Consider yourself as the user of your application and you accidentally break your device or reset to factory settings. At the same time, your application will be uninstalled from the device and when you install your application on a new device, everything is gone… very, very bad user experience… isn’t it?
Backing up your application data is truly what you need at this moment. You have to preserve the user’s data and personalize it when the user logs into another device.
There are two ways to backup your application data: Auto backup and key-value backup.
Auto backup
Introduced in Android 6.0, Auto backup is available for all higher versions. Here the application backups almost all the app files by default to Google drive of the same account to which the device is logged in with. Back up of data happens every day via wifi connection. The backup will never happen if the device never connects to wifi. However, the storage space is limit is 25 MB, in fact, Google does not count it in user allocated space.
Key-value backup
Introduced in Android 2.2, the key-value backup mechanism is available for all higher versions. In the key-value backup scenario, your app must implement a backup agent that defines the data to backup and how to restore the data. To put it differently, your application must issue a request when the data is ready for back up like all other applications. These requests are grouped, and execution happens every few hours either via Wifi or cellular network.
The storage space for this type of backup is even smaller as it restricts the backup data to limit only 5 MB.
what to save?
- Identity data
- Application data
- Settings data
what not to save?
- URI data
- large files
Advantages of data backup
- Restores data when the user logs into another device
- Save settings and user preferences
- Auto backup happens in android version 6.0 or higher.
Disadvantages of data backup
- Do not backup data if not connected to wifi
- storage size is very less
10. Firebase real-time database
You all must be familiar with firebase. Google offers firebase platform to help you develop and grow your applications and yes make money too. Firebase provides a number of features to implement in your application like Cloud messaging, Google analytics, AdMob, crashlytics, realtime database etc..
For data management, we use realtime database feature of the firebase which has the following characteristics:
- save and synchronize data with NoSQL cloud database.
- Stores data in JSON format.
- uses data synchronization instead of HTTP requests.
- Firebase database SDK persists in local disk. Hence, the application is responsive even when there is no internet connection.
To use firebase realtime database you have to register your application on firebase and download the firebase SDK to your application scope. In terms of cloud storage and realtime database, firebase is the best option to go for.
what to save?
Save structured data in firebase database, like what we save in SQLite and Realm databases.
what not to save?
- Media files like Images, Audios and Videos.
- Files
Advantages of firebase realtime database
- Realtime data update. Devices updates within milliseconds if there is any change in data.
- stores data offline in SDK so that app has data even when offline, as soon as it comes online, it syncs data again.
- can share data among applications.
- No fear of losing data.
Disadvantages of firebase realtime database
- the storage format is different from SQL so there will be a problem while migrating the data.
- It is free(no cost) to an extent- limited to 50 clients and 100mb of storage
Summing up
Guys! there are a lot of methods available in Android for storing data. Above listed methods are the mechanisms that a developer can use while building an application. For user End, the users also have various options to store the data like they can store their data in external hard drives or they can save the data on cloud storage. There are a lot of providers that give online storage like Google Drive, Dropbox and many more.
There are performance and security which you need to take care while opting for any of the methods above. So, Developers be wise and proceed according to your exact needs.
Meanwhile, Do like and comment and spread this information among peers. Thank you!
- LinkedIn Scraper | LinkedIn Data Extractor Software Tool - February 22, 2021
- Is Web Scraping Legal? - February 15, 2021
- What Is Data Scraping? - February 10, 2021
Great article with a nice breakdown of pros and cons. Thanks for the info!