An Android app typically requests data and then modifies that data to produce a result throughout multiple activities. With programs you have written so far, the values entered did not persist beyond the Activity in which they were created. The data was lost because it was being stored in RAM which is cleared each time the app is closed. To create persistent data that can be accessed over and over, Android apps can save data on the device’s drive or other storage media such as a memory card. This lesson will show you how to store data that your app can then retrieve and use.
Locations of Persistent Data
Android provides several options for saving application data based on the specific needs of the app. Some apps require private storage while others need to share data between apps.
There are five different places to store data:
- Shared Preferences – Stores data in key/value pairs
- Internal Storage – Stores private data in the memory of the device
- External Storage – Stores data, which can be available to other apps on shared external storage
- SQLite Databases – Stores structured data in a private database
- Network Connection – Stores data on a Web server
Retrieving Android data is just about as easy as saving it when you are working with SharedPreferences. The difference is that you do not need to setup an Editor in order to read data that has already been stored.
In addition to the Android system storage locations, Xamarin apps also have Application.Current.Properties which is implemented in Xamarin.Forms which allows you to store simple Key-Value pairs of data as well. The Properties dictionary is saved to the device automatically. Data added to the dictionary will be available when the application returns from the background or even after it is restarted.
Xamarin.Forms 1.4 introduced an additional method on the Application class – SavePropertiesAsync() – which can be called to proactively persist the Properties dictionary. This is to allow you to save properties after important updates rather than risk them not getting serialized out due to a crash or being killed by the OS.
This video will walk you through creating an app that stores information using the Shared Preferences. We will store data using an Editor and retrieve it. Retrieving Android data is just about as easy as saving it when you are working with SharedPreferences. The difference is that you do not need to setup an Editor in order to read data that has already been stored.