Android Base Data Persistence

What is Persistence? Android Internal Persistence Android External Persistence Android SQL Persistence Full Persistence Example Download Android Persistence Full Example

 

What is Persistence?

It talks about save our data, like when we are writing a letter, with the purpose that we can read or continue in a future time.

 

Definition of persistence

  • :1. intr. Staying steady or steady in something. 2. intr. Last for a long time

Android offers different options for you to keep persistent data of the application. The solution you choose depends on your specific needs; For example, whether the data should be private to your application or be available to other applications (and the user), and the amount of space your data requires.

Android Persistence

Android is a system based on Linux OS allowing permissions to be applied to the files, the main ones would be exclusive (private) access from the app or public, the common way of persistence data goes through the following destinies.

  • Store and Read Preferences.
  • Store and Read Data in files inside the App box.
  • Store and Read Data on External SD Card, App Domain and Public Domains (all apps could access).
  • Store and Read Data on Cache, App Internal and External Domains (store cache on SD Card).
  • Manage data like Database with SQLite3 only for the app.
  • Content Providers area useful to open a general interfaces to expose data to other apps.

All files are deleted when uninstalled the app, except the external public data (like photos) that keep stored in the public external folder. Also the cache files could be remove for the user from settings or by the system.

 

Let’s see each of this persistence ways and then a full example with explanation and code.

 

Store and Load User App Preferences

It allows you to save and retrieve persistent key-value pairs from primitive data types (boolean, floating elements, integer values, long values ??and strings). This data will be retained once the app is closed.

GetSharedPreferences () use this option if you need multiple preference files identified by name, which you specify with the first parameter.

Use this option GetPreferences() if you only need a preferences file for your activity. Because this will be the only preference file for your activity, you should not provide a name.

A preferences file always is managed by an Editor object, with which we work to assign the different values ??per type, and finally to set (commit) the changes. See the following example:

 

The other case is load the preferences, is this case We get the types directly from the settings (SharedPreferences Object).

 

 

How Check the Preferences File?

The Preferences file is stored into the app, an easy way to access is with the Android Tool adb, remember that the binary has to be on the system path and that we need be a root user to have permissions to access the directories and files.

Then we access to the shared_prefs folder.

The content of the Preferences File can be showed with the commands:

 

Great!, Let’s see the others persistence systems.

Internal App Storage for private data

To create a new file in one of these directories, you can use the File() constructor by passing the File provided by one of the previous methods specified by your internal storage directory.

For example:

We can store app-level files directly on the device’s internal storage. By default, files that are saved to internal storage are private to your application, and other applications can not access them (or the user). When the user uninstalls your application, these files are removed.

 

To create and write a private file to internal storage, do the following:

Calls openFileOutput() using the file name and operating mode. This shows a FileOutputStream(). Performs write operations on the file with write(). Close the flow with close().

When we open the file a mode must be specified, by default private mode is enable (only our app could access to the file) .

mode int: Operating mode. Use 0 or MODE_PRIVATE for the default operation. Use MODE_APPEND to append to an existing file.

Watch the following example, about how is the file created inside the app bundled, we are using the PrintWriter class with the idea to store easily a text file using the println() method. At the end we have two records in the file separated by a carriage return.

Remember to control the exceptions and at the close() moment check y if the object are not null. Great!

The opposite case is the opening to read the file, using the FileReader () class to open the file and the BufferedReader to read the records separated by carriage return.

 

 

How Check the Internal File?

The Preferences file is stored into the app, an easy way to access is with the Android Tool adb, remember that the binary has to be on the system path and that we need be a root user to have permissions to access the directories and files.

Then we access to the files folder.

The content of the file can be showed with the commands:

 

 

External Storage for Large Data

Obtain permissions for external storage

To write to external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:

To read is necessary the following:

However, if your app uses the WRITE_EXTERNAL_STORAGE permission, you also have implicit permission to read the external storage.

Device manufacturers can impose quite restrictive limits, perhaps as low as 150MB shared among all applications although this is not sure, currently apps stores Gbs files without problems. Take care to catch exceptions for problems referred to store problems.

 

To load from external we can use the next example, using the FileReader Class:

 

Save Public External Files

How to save external files to a “public” location on the device, on which other applications can access them, and the user can copy them from the device.

When you do, you must use one of the shared public directories, such as Music /, Pictures / and Ringtones /. To get a file representing the appropriate directory, call getExternalStoragePublicDirectory () and use the type of directory you want, such as DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES, or others.

When you save your files to the directory of the corresponding media types, the system media scanner can properly categorize your files in the system (for example, the tones are displayed in the system settings as tones, not music).

Save Private External Files

If you want to save private files from your app, you can get the corresponding directory by calling getExternalFilesDir () and giving it a name that indicates the type of directory you want. But note the files will still be accessible by other apps since we are in an external system, the difference is that uninstalling it will be automatically deleted.

Caution. Private external file are accesible by all apps installed on device. the difference is that uninstalling it will be automatically deleted

 

How Check the External File?

The External File is stored into the app, an easy way to access is with the Android Tool adb, remember that the binary has to be on the system path and that we need be a root user to have permissions to access the directories and files.

In the case of external, the file is stored on SD Card, it exists. The way of check is find the /storage folder content.

Then we access to the storage folder and show the content of file.

 

Cache Storage for Temporal Data

When the device has little internal storage space, Android can remove these cache files to recover space.

However, you should not trust that the system will erase these files. You should always take care to keep the cache files and keep them within a reasonable space limit, for example, 1 MB. When the user uninstalls your application, these files are removed.

Also you can create temporal random files with prefix and suffix.

To Load from internal cache, we use;

Again Great!

How Check the Cache File?

The Cache File is stored into the app, an easy way to access is with the Android Tool adb, remember that the binary has to be on the system path and that we need be a root user to have permissions to access the directories and files.

Then we access to the folder shared_prefs folder.

The content of the Preferences File can be showed with the commands:

SQLite Database Insert And Select Structured Storage

To work with databases Android system deliver a SQLite inside app (embedded) engine. To make it easy also exists an Android framework (SQLiteOpenHelper) that help us to create the database and the tables. The first time we create our DataBaseHelper (this class extends SQLiteOpenHelper) the onCreate method is executed automatically creating the User table.

For the User entity (table), an adapter has been built UserDBAdapter, this object encapsulate the dialog with the database for resolve the create, read (select), insert and delete sentences.

 

This interface is the one that the developer use from his code, let’s see the examples of save data into database:

 

And then the example of how load the data from the User table.

 

How Check the SQL Data?

The SQL Data is stored on a db file into the app, an easy way to access is with the Android Tool adb, remember that the binary has to be on the system path and that we need be a root user to have permissions to access the directories and files.

The folder is databases and contains the User file (db), inside we can find the User table and its content, let’s see:

 

Content Providers

Content providers and content solvers are solutions to allow information sharing between applications. An application that wants all or part of the information it stores to be available in a controlled way for the rest of the applications of the system must provide a content provider through which the information can be accessed. Let’s say it is a kind of standardization of data access between applications through URLs. Will be studied in the advanced course.

Full Persistence Example

This demo shows how work with the different storage. We have a layout with all options

The layout link the “Loading” & “Saving” actions buttons with the method. This method persistenceOnClick do the validation of data, basically that the UserName & UserAge are filled and the age must be a number. Besides we are tagged the action with the aim of make an special validation when try load data from SQLite, in that case we need a key for look up a register.

Next the fragment code of layout with tag “save” and “load” and onclick action link to persistenceOnClick:

Following code of persistenceOnClick, firts line resolve the validation if all was ok continue with each persistence option in function of view ID:

To request permissions on-demand for read or write is necessary defined at the manifest and then check (shouldShowRequestPermissionRationale) if it was granted or not, in last case we must to call shouldShowRequestPermissionRationale to show the permission dialog.

Once we have requested the permissions we have to listen to the acceptance by the user, if yes the external storage is executed, as long as the unit (SD card normally) is available. (to watch all behavior access to net video Video Save And Visualize External Private)

Also in the moment of read or write we check if the external storage is mounted, as we said before.

 

 

Video Save And Visualize User Preferences

Video Save And Visualize Internal File

Video Save And Visualize Internal Cache

Video Save And Visualize External Private

Video Save And Visualize DB Data

Video Show All Data & Delete Stores

Conclusions

In a summary work with different storage levels:

  • Store and Read Preferences.
  • Store and Read Data in files inside the App box.
  • Store and Read Data on External SD Card, App Domain and Public Domains (all apps could access).
  • Store and Read Data on Cache, App Internal and External Domains (store cache on SD Card).
  • Manage data like Database with SQLite3 only for the app.
  • Content Providers area useful to open a general interfaces to expose data to other apps. We are going to study in Advanced level.

Remember all files are deleted when uninstalled the app, except the external public data (like photos) that keep store in the public external folder. Private External Files are accesible by all apps installed on device and  also are deleted when the app is uninstalled.

Good job, let’s move on to the next chapter on user Logging And Debug, you get along very well.

 

Download Android Persistence Full Example

PreferencesAndPersistence

All Downloads

https://bitbucket.org/keikisacademy/keikis-academy-android

git clone https://bitbucket.org/keikisacademy/keikis-academy-android.git

Info Links

Portions of this page are reproduced from work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
https://developer.android.com/guide/topics/data/data-storage.html

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Reply

Social media & sharing icons powered by UltimatelySocial