Storing and Retrieving
Storing and Retrieving
DATA
INTRODUCTION
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
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Using Android External Storage
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 :
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();
@Override
protected void onDestroy()
{
dbHelper.close();
super.onDestroy();
}
CONCLUSION