CH 4
CH 4
Android provides many kinds of storage for applications to store their data. These storage places
are shared preferences, internal and external storage, SQLite storage, and storage via network
connection.
In this chapter we are going to look at the internal storage. Internal storage is the storage of the
private data on the device memory.
By default these files are private and are accessed by only your application and get deleted ,
when user delete your application.
Writing file
In order to use internal storage to write some data in the file, call the openFileOutput() method
with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is
given below −
fOut.write(str.getBytes());
fOut.close();
Reading file
In order to read from the file you just created , call the openFileInput() method with the name of
the file. It returns an instance of FileInputStream. Its syntax is given below −
After that, you can call read method to read one character at a time from the file and then you
can print it. Its syntax is given below −
int c;
String temp="";
fin.close();
The SharedPreferencesclass provides a general framework that allows you to save and retrieve
persistent key-value pairs of primitive data types. You can use SharedPreferencesto save any
primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions
(even if your application is killed).
User Preferences
Shared preferences are not strictly for saving “user preferences,” such as what ringtone a user has
chosen. If you’re interested in creating user preferences for your application, see
PreferenceActivity, which provides an Activity framework for you to create user preferences,
which will be automatically persisted (using shared preferences).
getSharedPreferences() – Use this if you need multiple preferences files identified by name,
which you specify with the first parameter.
getPreferences() – Use this if you need only one preferences file for your Activity. Because this
will be the only preferences file for your Activity, you don’t supply a name.
To write values:
Here is an example that saves a preference for silent keypress mode in a calculator:
@Override
super.onCreate(state);
...
// Restore preferences
setSilent(silent);
@Override
super.onStop();
editor.putBoolean("silentMode", mSilentMode);
editor.commit();
If you’d like to cache some data, rather than store it persistently, you should use getCacheDir()to
open a Filethat represents the internal directory where your application should save temporary
cache files.
When the device is low on internal storage space, Android may delete these cache files to
recover space. However, you should not rely on the system to clean up these files for you. You
should always maintain the cache files yourself and stay within a reasonable limit of space
consumed, such as 1MB. When the user uninstalls your application, these files are removed.
getFilesDir()
Gets the absolute path to the filesystem directory where your internal files are saved.
getDir()
Creates (or opens an existing) directory within your internal storage space.
deleteFile()
fileList()
If you’re using API Level 8 or greater, use getExternalFilesDir()to open a Filethat represents the
external storage directory where you should save your files. This method takes a typeparameter
that specifies the type of subdirectory you want, such asDIRECTORY_MUSICand
DIRECTORY_RINGTONES(pass nullto receive the root of your application’s file directory).
This method will create the appropriate directory if necessary. By specifying the type of
directory, you ensure that the Android’s media scanner will properly categorize your files in the
system (for example, ringtones are identified as ringtones and not music). If the user uninstalls
your application, this directory and all its contents will be deleted.
/Android/data/<package_name>/files/
Using Databases
Android provides full support for SQLite databases. Any databases you create will be accessible
by name to any class in the application, but not outside the application.
DictionaryOpenHelper(Context context) {
@Override
db.execSQL(DICTIONARY_TABLE_CREATE);
You can then get an instance of your SQLiteOpenHelperimplementation using the constructor
you’ve defined. To write to and read from the database, call getWritableDatabase()and
getReadableDatabase(), respectively. These both return a SQLiteDatabaseobject that represents
the database and provides methods for SQLite operations.
Android does not impose any limitations beyond the standard SQLite concepts. We do
recommend including an autoincrement value key field that can be used as a unique ID to
quickly find a record. This is not required for private data, but if you implement acontent
provider, you must include a unique ID using the BaseColumns._IDconstant.
You can execute SQLite queries using the SQLiteDatabasequery()methods, which accept various
query parameters, such as the table to query, the projection, selection, columns, grouping, and
others. For complex queries, such as those that require column aliases, you should use
SQLiteQueryBuilder, which provides several convienent methods for building queries.
Every SQLite query will return a Cursorthat points to all the rows found by the query. The
Cursoris always the mechanism with which you can navigate results from a database query and
read rows and columns.
For sample apps already send by me that demonstrate how to use SQLite databases in Android.
By using the content provider, data can be shared across applications. The content provider is a
set of data wrapped up in a custom API to read and write. Applications/Processes have to register
themselves as a provider of data. Other applications can request Android to read/write that data
through a fixed API.
Contacts are the best example – that exposes user information to other applications, Media store-
Allows other applications to access, store media files.
There is some standard methods – insert(), query(), update(), delete(), to access application data.
So it is easy to implement a content provider.
We need to assign a URI to each Content Provider, starting with “content://” and that will be
recognized by applications.
1. content:// – The content provider URIs should start with this value.
2. ‘authority’ – This is Java namespace of the content provider implementation passes the
Java package name.
3. ‘path’ – This is a virtual directory within the provider that identifies, what kind of data
being requested.
4. ‘id’ – This is an optional part that specifies the primary key of a record being requested.
This part can be ignored to access all data.
Add data:
We need to override insert() method. If data inserted successful, it will return the URI value with
the associated with ID.
Updating data:
Deleting data:
delete() method of the ContentProvider will return the number of records deleted.
<provider
android:name=".MyProvider"
android:authorities="packageName.MyProvider">
</provider>