Tuesday, June 24, 2014

Android Data Storage - Details


There are many ways the data can be stored on an Android device. The solution which should be picked up depends on whether the data should be stored as private or should be accessible to other applications also. 

Below are the data storage options: 

1. Shared preferences
2. Internal Storage 
3. External Storage
4. SQLite Databases
5. Network Connection 

Even though the private data cannot be accessed from other application, The application itself can share the private data in a restricted manner using ContentProviders. 

Shared Preferences
This can be used to provide general framework that allows user to save and retrieve persistent key-value pairs of primitive data types. There are two ways the SharedPreference can be accessed. 

1. getSharedPreferences() - Use this method if the application needs multiple preference files identified by name, which you specify with the first parameter. 
2. getPreferences() - Use this if application needs only one preference file for the Activity. Because this is the only activity, there is no need to supply a name. 

To write the values below are the steps

1. Call Edit to get the shared preference editor - edit() method will give SharedPreferences.Editor 
2. user putString, putBoolean to add values to the shared preferences 
3. commit new values using commit() 

To read the values, application can use getBoolean, getString methods. 

Using Internal Storage
To store the data directly on internal storage which is private to the app can be done via the FileOutputStream. Below is the code to accomplish this

1. Call openFileOutput, which will return FileOutputStream
2. write to the file with write()
3. close using close() 

when calling the openFileOutput, application can specify the mode, for e.g. something like below 

FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
fos.write(string.bytes); 

fos.close(); 

No comments:

Post a Comment