0% found this document useful (0 votes)
25 views19 pages

Storing and Retrieving

Uploaded by

Tejasree M.S.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views19 pages

Storing and Retrieving

Uploaded by

Tejasree M.S.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

STORING & RETRIEVING

DATA
INTRODUCTION

 Android provides several ways to store and share data :


 Access to the file-system via a local relational database through SQLite
 A preferences system that allows you to store simple key/value pairs
within applications.
SHARED PREFERENCES SYSTEM

 Shared Preferences is the way in which one can store and retrieve
small amounts of primitive data as key/value pairs to a file on the device
storage such as String, int, float, Boolean that make up your preferences
in an XML file inside the app on the device storage.
 Shared Preferences class provides APIs for reading, writing, and
managing this data.
 Use cases of Shared Preferences :

 when the user’s settings need to be saved or to store data that can
be used in different activities within the app
 onPause() - called before your activity is placed in the background
or destroyed, data is saved persistently.
 onCreate() – to restore the data being saved persistently
Shared Preferences vs Saved Instance State
Shared Preferences Saved Instance State
Persist Data across user sessions, Preserves state data across
even if the app is killed and activity instances in the same
restarted, or the device is user session.
rebooted

Data that should be remembered Data that should not be


across sessions, such as the remembered across sessions,
user’s preferred settings or their such as the currently selected
game score. tab or current state of activity.

A common use is to store user A common use is to recreate the


preferences state after the device has been
rotated
To create and access the Shared Preferences
 Shared Preferences provide modes of storing the data (private mode and
public mode).
• MODE_PUBLIC will make the file public which could be accessible by other
applications on the device
• MODE_PRIVATE keeps the files private and secures the user’s data.
• MODE_APPEND is used while reading the data from the SP file.

 Nested classes of Shared Preferences


• SharedPreferences.Editor: Interface used to write(edit) data in the SP file.
Once editing has been done, one must commit() or apply() the changes
made to the file.
• SharedPreferences.OnSharedPreferenceChangeListener(): Called
when a shared preference is changed, added, or removed. This may be
called even if a preference is set to its existing value. This callback will be
run on your main thread.
USING THE FILE SYSTEM
 Android’s filesystem is based on Linux and supports mode-based
permissions. You can access this filesystem in several ways.
 You can create and read files from within applications, you can access
raw resource files, and you can work with specially compiled custom
XML files.
Files as raw resources
 The res/values folder is used to store the values for the resources that
are used in many Android projects to include features of color, styles,
dimensions etc.
 Accessing a compiled XML resource from res/xml :
External Storage via an SD card

 Offering access to an available SD flash memory card.


 All applications can read and write files placed on the external storage
and the user can remove them. We need to check if the SD card is
available and if we can write to it. Once we’ve checked that the external
storage is available only then we can write to it else the save button
would be disabled.
 Firstly, we need to make sure that the application has permission to read
and write data to the users SD card, so AndroidManifest.xml file needs
to be modified.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Using Android External Storage

1. Environment.getExternalStorageState(): returns path


to internal SD mount point like “/mnt/sdcard”
2. getExternalFilesDir(): It returns the path to files folder
inside Android/data/data/application_package/ on the SD
card. It is used to store any required files for your app (like
images downloaded from web or cache files). Once the app
is uninstalled, any data stored in this folder is gone too
SQLite Relational Database in Android

 opensource SQL database that stores data to a text file on a device.


Android comes in with built in SQLite database implementation.
 In order to access this database, you don't need to establish any kind of
connections for it like JDBC,ODBC e.t.c
 Database Creation:

SQLiteDatabase mydatabase = openOrCreateDatabase("your database


name",MODE_PRIVATE,null);

 Database Insertion:
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS tablename(Username VARCHAR,Password
VARCHAR);"); mydatabase.execSQL("INSERT INTO tablename VALUES('admin','admin');");
 To create a database in SQLite in Android, you need to create a
subclass of the class SQLiteOpenHelper.
 This class provides the functionality to create a database and calls a
function that can be overridden by the derived class.
 The SQLiteOpenHelper constructor accepts four arguments, which
are :

1. Context – This is the context that will be used to create the


database. (Here you can pass the Activity object.)
2. Name – The name of the new database file.
3. Factory – A cursor factory (you can usually pass this as null)
4. Version – The version of the database. This number is used to
identify if there is an upgrade or downgrade of the database.
Adding Values within the Database
 The insert function takes three arguments: the name of the table in
which to insert values, the name of one of the column of the table, and a
reference to a ContentValues

public void addFriend(String name,int phonenumber)


{
ContentValues values=new ContentValues(2);
values.put("name", name);
values.put("phonenumber", phonenumber);
getWritableDatabase().insert("friends", "name", values);
}

In this function, we take the input arguments as the name and


the phonenumber. Then, we create a new object of ContentValues,
we put the values for name and phonenumber within that new
object. Once we have done that, we get the SQLiteDatabase
reference for writing using the function getWritableDatabase,
which is a member of SQLiteOpenHelper.
Read information from the database
• To read from a database, use the query() method, passing it your
selection criteria and desired columns.
• The method combines elements of insert() and update(), except the
column list defines the data you want to fetch (the "projection"),
rather than the data to insert.
• The results of the query are returned to you in a Cursor object.
SQLiteDatabase db = dbHelper.getReadableDatabase();

// Filter results WHERE "title" = 'My Title'


String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" };
Cursor cursor = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The array of columns to return (pass null to
get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Delete information from the database
• To delete rows from a table, you need to provide selection criteria that identify the
rows to the delete() method.
• The mechanism works the same as the selection arguments to the query() method.
It divides the selection specification into a selection clause and selection
arguments.
// Define 'where' part of query.
String selection = FeedEntry.COLUMN_NAME_TITLE + " LIKE ?";
// Specify arguments in placeholder order.
String[] selectionArgs = { "MyTitle" };
// Issue SQL statement.
int deletedRows = db.delete(FeedEntry.TABLE_NAME, selection,
selectionArgs);

The return value for the delete() method indicates the number of rows that were deleted
from the database.
Update a database
When you need to modify a subset of your database values, use the update()
method.
Updating the table combines the ContentValues syntax of insert() with
the WHERE syntax of delete().
SQLiteDatabase db = dbHelper.getWritableDatabase();

// New value for one column


String title = "MyNewTitle";
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);

// Which row to update, based on the title


String selection = FeedEntry.COLUMN_NAME_TITLE + "
LIKE ?";
String[] selectionArgs = { "MyOldTitle" };

int count = db.update(


FeedReaderDbHelper.FeedEntry.TABLE_NAME,
values,
selection,
selectionArgs);
Persisting database
connection
• Since getWritableDatabase() and getReadableDatabase() are
expensive to call when the database is closed, you should
leave your database connection open for as long as you
possibly need to access it.
• Typically, it is optimal to close the database in the onDestroy()
of the calling Activity.

@Override
protected void onDestroy()
{
dbHelper.close();
super.onDestroy();
}
CONCLUSION

 Data is the most important part of today’s competitive apps. A well-built


app must store and retrieve data efficiently and with ease, so that it can
function smoothly and please users.
 Android provides several forms of good support to store data in
databases for your Android apps.
 It provides all the functionality to create and update SQLite databases
and database tables.

You might also like