Lecture-13-Data-Persistence
Lecture-13-Data-Persistence
Data Persistence
DATA PERSISTENCE WITH
SHARED PREFERENCES
Shared Preferences
• If you have a relatively small collection of key‐values that
you'd like to save, you should use the SharedPreferences
APIs.
• A SharedPreferences object points to a file containing key‐
value pairs and provides simple methods to read and write
them.
• Each SharedPreferences file is managed by the framework
and can be private or shared.
Shared Preferences
• The SharedPreferences APIs are only for reading and writing
key‐value pairs and you should not confuse them with the
Preference APIs, which help you build a user interface for
your app settings (although they use SharedPreferences as
their implementation to save the app settings).
Shared Preferences
• You can create a new shared preference file or access an
existing one by calling one of two methods:
– getSharedPreferences() — Use this if you need multiple shared
preference files identified by name, which you specify with the first
parameter. You can call this from any Context in your app.
fn="Some Name";
SharedPreferences sharedPreferences =
getSharedPreferences("pk.edu.riu.e4031.share_preference_file_ke
y", MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("full_name",fn);
editor.commit();
Shared Preferences
Retrieve Shared Preferences:
SharedPreferences sharedPreferences =
getSharedPreferences("pk.edu.riu.e4031.share_preference_file_ke
y",MODE_PRIVATE);
String helloText =
sharedPreferences.getString("full_name",“Default Value");
DATA PERSISTENCE WITH
SQLITE DATABASE
What is SQLite?
• SQLite is a software library that implements a self‐contained,
serverless, zero‐configuration, transactional SQL database
engine.
– It requires very minimal support from external libraries or from the
operating system
– With SQLite, the process that wants to access the database reads and
writes directly from the database files on disk.
– SQLite does not need to be "installed" before it is used.
– With SQLite if anything goes wrong during a transaction, it is rolled
back automatically.
• http://www.w3schools.com/sql/
Sample Application
How to Use SQLite Database
• Define a Schema
– You can create your own database adapter to handle these operations.
Define Schema
Define Schema
• The schema is reflected in the SQL statements that you use to
create your database.
public DatabaseContract() { }
}
Define Schema in Contract Class
• By implementing the BaseColumns interface, your inner class
can inherit a primary key field called _ID that some Android
classes such as cursor adaptors will expect it to have.
• It's not required, but this can help your database work
harmoniously with the Android framework.
SQLiteOpenHelper
SQLiteOpenHelper
• Once you have defined how your database looks, you should
implement methods that create and maintain the database
and tables.
. . .
}
onCreate()
public class DatabaseHelper extends SQLiteOpenHelper {
. . .
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// TODO Auto-generated method stub
}
}
onCreate()
public class DatabaseHelper extends SQLiteOpenHelper {
. . .
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_BOOKS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// TODO Auto-generated method stub
}
}
onUpgrade()
• Called when database needs to be upgraded.
For Example:
– public static final int DATABASE_VERSION = 2;
. . .
}
onUpgrade()
public class DatabaseHelper extends SQLiteOpenHelper {
. . .
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_BOOKS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// TODO Auto-generated method stub
}
}
onUpgrade()
public class DatabaseHelper extends SQLiteOpenHelper {
. . .
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_BOOKS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
if (oldVersion<2) {
db.execSQL(ALTER_TABLE_BOOKS);
}
}
}
Use SQLiteDatabase
Using SQLiteDatabase
• To access your database, create an instance of extended
SQLiteOpenHelper class:
DatabaseHelper dbHelper = new DatabaseHelper(getContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
SQLiteDatabase db = dbHelper.getReadableDatabase();
SQLiteDatabase insert() Method
• Method for inserting a row into the database.
• Parameters
– table the table to insert the row into
– nullColumnHack optional; may be null. SQL doesn't allow inserting a completely empty
row without naming at least one column name. If your provided values is empty, no
column names are known and an empty row can't be inserted. If not set to null, the
nullColumnHack parameter provides the name of nullable column name to explicitly
insert a NULL into in the case where your values is empty.
– values this map contains the initial column values for the row. The keys should be the
column names and the values the column values
• Returns the row ID of the newly inserted row, or ‐1 if an error occurred
SQLiteDatabase query() Method
• Method to query the given table, returning a Cursor over the result set.
• Parameters
– table the table to delete from
– whereClause the optional WHERE clause to apply when deleting. Passing null will delete
all rows.
– whereArgs You may include ?s in the where clause, which will be replaced by the values
from whereArgs. The values will be bound as Strings.
• Returns the number of rows affected if a whereClause is passed in, 0 otherwise.
SQLiteDatabase update() Method
• Method for for updating rows in the database.
• Parameters
– table the table to update in
– values a map from column names to new column values. null is a valid value that will be
translated to NULL.
– whereClause
– whereClause the optional WHERE clause to apply when updating. Passing null will
update all rows.
– whereClause You may include ?s in the where clause, which will be replaced by the
values from whereArgs. The values will be bound as Strings..
• Returns the number of rows affected
ADDING NEW RECORD
Adding New Record
SQLiteDatabase insert() Method
• Method for inserting a row into the database.
• Parameters
– table the table to insert the row into
– nullColumnHack optional; may be null. SQL doesn't allow inserting a completely empty
row without naming at least one column name. If your provided values is empty, no
column names are known and an empty row can't be inserted. If not set to null, the
nullColumnHack parameter provides the name of nullable column name to explicitly
insert a NULL into in the case where your values is empty.
– values this map contains the initial column values for the row. The keys should be the
column names and the values the column values
• Returns the row ID of the newly inserted row, or ‐1 if an error occurred
Adding New Record
String val1="Some Book Title";
String val2="Some Author";
SQLiteDatabase db = dbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(Books.COL_TITLE, val1);
values.put(Books.COL_AUTHOR, val2);
if (id>0) {
Toast.makeText(this, "New Record Inserted: " + id,
Toast.LENGTH_SHORT).show();
}
db.close(); // Closing database connection
QUERY ALL RECORDS
Query All Records
Query All Records
• Add ListView
• SetOnItemClickListener
Add ListView
<RelativeLayout ...>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
SQLiteDatabase query() Method
• Method to query the given table, returning a Cursor over the result set.
String[] columns={Books._ID,Books.COL_TITLE,Books.COL_AUTHOR};
// String whereClause="";
// String[] whereArgs={};
// String having="";
// String groupBy="";
String orderBy= Books.COL_TITLE + " ASC";
<LinearLayout . . .>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:textSize="20sp"
android:text="Book Title"
android:id="@+id/txt_title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Book Author"
android:id="@+id/txt_author"/>
</LinearLayout>
</LinearLayout>
Create Custom CursorAdapter
public class BooksCursorAdapter extends CursorAdapter {
public BooksCursorAdapter(Context context, Cursor cursor) {
super(context,cursor,0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO
}
}
Create Custom CursorAdapter
public class BooksCursorAdapter extends CursorAdapter {
. . .
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
return
LayoutInflater.from(context).inflate(R.layout.all_books,parent,false);
}
. . .
}
Create Custom CursorAdapter
public class BooksCursorAdapter extends CursorAdapter {
. . .
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tvId=(TextView) view.findViewById(R.id.txt_id);
TextView tvTitle=(TextView) view.findViewById(R.id.txt_title);
TextView tvAuthor=(TextView) view.findViewById(R.id.txt_author);
tvId.setText(String.valueOf(cursor.getInt(cursor.getColumnIndexOrThrow(B
ooks._ID))));
tvTitle.setText(cursor.getString(cursor.getColumnIndexOrThrow(Books.COL_
TITLE)));
tvAuthor.setText(cursor.getString(cursor.getColumnIndexOrThrow(Books.COL
_AUTHOR)));
}
}
Set CursorAdapter on ListView
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] columns={Books._ID,Books.COL_TITLE,Books.COL_AUTHOR};
String orderBy= Books.COL_TITLE + " ASC";
}
});
BookActivity.class
. . .
Intent i=getIntent();
long bid=i.getLongExtra("bookId",0);
. . .
QUERY SINGLE RECORD
Query Single Record
Query Single Record
String[] columns={Books._ID,Books.COL_TITLE,Books.COL_AUTHOR};
String whereClause=Books._ID + "=?";
String[] whereArgs={ String.valueOf(bid) };
// String having="";
// String groupBy="";
// String orderBy="";
Cursor cursor=db.query(Books.TABLE_NAME, columns, whereClause,
whereArgs, null, null, null);
if (cursor!=null) {
cursor.moveToFirst();
et1.setText(cursor.getString(cursor.getColumnIndexOrThrow(Books.COL
_TITLE)));
et2.setText(cursor.getString(cursor.getColumnIndexOrThrow(Books.COL
_AUTHOR)));
}
cursor.close();
DELETE RECORD
Delete Record
SQLiteDatabase delete() Method
• Method for deleting rows in the database.
• Parameters
– table the table to delete from
– whereClause the optional WHERE clause to apply when deleting. Passing null will delete
all rows.
– whereArgs You may include ?s in the where clause, which will be replaced by the values
from whereArgs. The values will be bound as Strings.
• Returns the number of rows affected if a whereClause is passed in, 0 otherwise.
Delete Record
SQLiteDatabase db = dbHelper.getWritableDatabase();
• Parameters
– table the table to update in
– values a map from column names to new column values. null is a valid value that will be
translated to NULL.
– whereClause
– whereClause the optional WHERE clause to apply when updating. Passing null will
update all rows.
– whereClause You may include ?s in the where clause, which will be replaced by the
values from whereArgs. The values will be bound as Strings..
• Returns the number of rows affected
Update Record
EditText et1=(EditText) findViewById(R.id.bookTitle);
EditText et2=(EditText) findViewById(R.id.bookAuthor);
String title=et1.getText().toString();
String author=et2.getText().toString();
• http://developer.android.com/guide/topics/data/data‐storage.html#db
• http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
• http://developer.android.com/reference/android/content/ContentValues.html
• http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
• http://developer.android.com/training/basics/data‐storage/shared‐preferences.html