Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Data persistence in Android

See in this article possible data persistence solutions to properly meet the needs of your Android applications.

Android provides several options for saving data persistent applications. The solution that is chosen will depend on specific needs, such as whether the data should be deprived of their application or accessible to other applications (and user) and how much space your data require.

We will show the following forms of storage in this article:

  • SharedPreferences:store primitive private data on key-value pairs.
  • Internal Storage: store private data in the device memory. (With object persistence)
  • External Storage: store public data on the shared external storage.
  • SQLite Databases: store structured data in a private database.

SharedPreferences

The SharedPreferences class allows you to save and retrieve key / value pairs of primitive data types. We can use the SharedPreferences to save the primitive data: booleans, floats, ints, longs, and strings. These data will persist in the user session (even if your application is dead).

For an SharedPreferences object to your application, use one of two methods:

  • getSharedPreferences (String name, int mode) - Use if you need several preferences files identified by name that will be passed in the first parameter.
  • getPreferences (int mode) - Use if you just need a preferences file for your activity.

To write values:

  • Call the method edit () to get a SharedPreferences.Editor;
  • Add values methods such as putBoolean () and putString ();
  • Persists the new values with commit ().

To read SharedPreferences values use the methods as getBoolean () and getString ().

Below is an example of storing and removing data from a preference:

Listing 1. Example of persistence with SharedPrefereces

public static final String PREFS_NAME = "MyPrefsFile";
private boolean test;
private void store(){
  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putBoolean("test", test);


  // Commit editings
  editor.commit();
}


private void recover(){
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   test = settings.getBoolean("test", false);
}

Internal storage

You can save files directly on the device's internal memory. By default, files saved to the internal storage are deprived of their application, allowing other applications can not access them. When the user uninstalls the application, these files are removed.

To create and save a private file to the internal storage:

  • Call openFileOutput () with the file name and the operating mode (in case MODE_PRIVATE). This returns a FileOutputStream;
  • Write on file with the write ();
  • Close the stream with close ().

Example:

Listing 2. Example of simple persistence with FileOutputStream

String FILENAME = "hello_file";
String string = "hello world!";


FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

Despite the advantage of record on file is not this, this feature is used effectively to record more complex files or even serializable objects.

We may record any disk object if it implements the Serializable interface java.io package, this allows us to build a standard configuration object, better managing persistent data. But remember that if we change that object after recording it will generate a deserialization problem when we try to return it to memory.

Here is an example of an object that implements Serializable:

Listing 3. Object with the Serializable interface

public class ObTest implements  Serializable {
    private int code;
    private String description;
    public ObTest(int code, String description) {
        this.code = code;
        this.description = description;
    }
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}


Given the class to write it just follow the step of Listing 2, but we record the subject as a whole see:

Listing 4. Recording serializable object
String FILENAME = "hello_file";
File file =getFileStreamPath(FILENAME);

FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(objeto);
oos.close();
fos.close();

FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
ObTest retorno = (ObTest) ois.readObject();
fis.close();
ois.close();

External storage

Each Android-compatible device supports an "external memory" shared that you can use to save files. This may be removable storage media (such as an SD card) or an internal memory (not removable). Files saved to the external storage are reading for all and can be modified by the user when they allow USB mass storage to transfer files from a computer.

Before doing any work with the external storage, you should always call Environment.getExternalStorageState () to check that the media is available. The media can be mounted to a computer, missing, read-only, or in some other state.

Listing 5: Checking state average
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

Access files on external storage

Let's use the getExternalFilesDir () feature to open a File representing the external storage directory where you should save your files. This method requires a parameter type that specifies the type of sub-directory you want, such as: Environment.DIRECTORY_MUSIC and Environment.DIRECTORY_RINGTONES (null to receive the root of your application directory). This method will create the appropriate directory, if necessary. When specifying the type of directory, you ensure that the Android media scanner will be properly categorized in your system files (eg ringtones are identified as ringtones rather than music). If the user uninstalls the application, this directory and all its contents is deleted.

If you want to save the files that are not specific to your application and that should not be deleted when the application is uninstalled, these directories should be at the root of external storage such as Music /, Pictures / Ringtones /, and others. To do this we use the Environment.getExternalStoragePublicDirectory () method, passing the kind of public directory you want, as Environment.DIRECTORY_MUSIC, Environment.DIRECTORY_RINGTONES or others. This method will create the appropriate directory, if necessary.

The recording method is similar to the examples already shown using FileOutputStream and Input to read.

Listing 6: Opening file public and writing data
        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File file = new File(dir, "test.obj");

        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(objeto);

SQLite database

A database is very useful for any large or small system, unless your system deals only with simple data, without using a bank to store information.

The Android uses the SQLite database that is open-source and widely used in popular applications. Other examples of who uses the SQLite are Mozilla Firefox and iPhone.

Android in the database that you create in an application is only available for the same, unless you use a content provider. Once you have created the database, it is stored in the directory "/ data / data / {package name} / databases / database {name}", and manage the code bank you can do so by using the adb sqlite3 tool.

The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate () method, in which you can run a SQLite command to create tables in the database.

Here's how to create the database manager:

Listing 7: Class responsible for managing the database
public class DB extends SQLiteOpenHelper {

    public DB(Context context, String name, int version) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase sqld) {
        sqld.execSQL("CREATE TABLE users_tbl ("
                + "id_users INTEGER PRIMARY KEY autoincrement,"
                + " user varchar(45) NOT NULL ,"
                + " pass varchar(45) NOT NULL,"
                + " name varchar(45) NOT NULL"
                + ");");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqld, int i, int i1) {
        //IMPLEMENTAR
    }
}


To use we instantiate it passing the name and version (starts at 1), if the version is changed, the ONUPGRADE method is called and there can make any kind of treatment to change the bank.

After instantiating'll have access to the bank through getWritableDatabase () method, with him we can insert, delet, update, select among other features.

Listing 8: Using the Bank class
DB db = new DB(this, "blaa", 1);

//Insert
ContentValues contentValues = new ContentValues();
contentValues.put("user", "test");
contentValues.put("pass", "123");
contentValues.put("name", "Test Test");
db.getWritableDatabase().insert("users_tbl", null, contentValues);

Cursor cursor = db.getWritableDatabase().query("users_tbl", new String[]{"user", "name"}, null, null, null, null, null);
while (cursor.moveToNext()) {
	System.out.println("-> " + cursor.getString(0));
	System.out.println("-> " + cursor.getString(1));
}

cursor.close();

Conclusion

In almost all developed software we need data persistence, imagine a system that contains a username and password, or even a settings menu where you can have a own profile. All these systems tend to store data on your device, the persistent resource should be studied thoroughly to choose the best way of doing so do not use advanced features in single or vice versa systems.

With that I conclude this article, a big hug and thank you.

References

Developer Android, Using Shared Preferences, accessed 1/16/2013


Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login