Most android apps require saving information between client sessions. We would want to save each type of data according to its purpose and when we’re going to use it. Android platform provides several methods to handle your data and persisting it.
- Shared Preferences – saving key-value pairs of primitive types. This data will persist across user sessions (even if your application is killed).
- Internal Storage – storing private data on the device memory. This data will be saved inside private files on the device internal memory. Other apps can not read those files and neither the user. When uninstalling the app, those files are automatically removed.
- External Storage – saving data inside files on an external storage such as SD card. This data is public and available to everyone. Also, this data can become unavailable if the user mounts the external storage or removes the media.
- SQLite Databases – storing private data inside a local MySQL Database. All classes inside the app can read and write this data.
Saving data inside tables can be very useful and convenient. Many web applications use relational data structures to store information. Android provides an internal MySQL DB for each application. This database is private for each app so you can be sure other apps won’t be able to read your app data.
Google’s best practice is to extend SQLiteOpenHelper and override the onCreate method.
Let us start by creating the model class of the instances we will save inside the DB. Each item is a simple Alarm instance
The next class provides a helper class for using the DB. We would give CRUD operations ability from this class. The database is created and updated according to the version be defined. You must make sure each time you alter the DB structure to increment the version integer also.
Finally, we will create a manager class to manage the specific DB calls from our app. This layer can perform extra operations before persisting new Alarms or querying them.
In order the execute queries, make sure you first initialize DbManage by calling the initialize method from the HomeActivity class
Querying the DB is simple as that
List<Alarm> alarms = DbManager.instance().getAllAlarms();