Tuesday, July 15, 2014

Permanently saving game or application settings on an android device.

If your application contains a good amount of customizable preferences, you will have to integrate into it the capability to save these preferences permanently. There are 2 ways to do this. One is to create an SQLite database and store the settings into it and the other is to create a simple file and store these settings in your own format.

Dealing with an SQLite database isn't that straight forward and should be avoided unless you really need what it has to offer. A database is suited for saving information is in a standardized manner so that this information can easily be used by multiple applications. These applications maybe developed by different developers, but since the information in a standard structure, they can create apps. that can process the information contained in this database without much effort. An example would be a dictionary database which stores a large amount of words, their meanings, word class etc. A database like this can be easily migrated for use from one app to another.

Using an SQLite database to store some simple application settings would be an overkill. It is much faster and easier to store and retrieve these using a simple binary file. Let's see how this can be done.


Here I will create a class called GameSettings which will hold the settings data and a class GameDataManager which will be responsible for writing and retrieving data from the external storage.

Add the necessary permissions to the manifest first.

The GameSettings class contains 4 variables.

1. difficulty - Determines the game difficulty
2. controller - Whether to use touch or accelerometer.
3. soundEnabled - Whether sound is on or off.
4. defaultSettings - A static string variable which holds the default values of all the above variables.

GameSettings class:

GameDataManager:

Once you have these 2 classes, create a new GameDataManager instance. If it's the first time the game/app is running, this will create a new settings file with the default settings at the specified location.
Now you can call the GameDataManager.getData() function to get an instance of GameSettings. Call GameDataManager.writeData() after updating any settings value. Edit both these classes according to your need.

Below is a sample use of these classes.


No comments:

Post a Comment