Module - 5: Persisting Data
Module - 5: Persisting Data
Persisting data
BSC/BCA S6 – S.A
1.Saving simple Application Data
➢ Android offers a robust and flexible framework for dealing with preferences.
➢ Preference is a feature choice the user makes and saves to customize the
application. Example- Setting notification via ringtone or vibration.
➢ The application remembers the choice until the user changes it.
6 MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences
Sr. NO Mode & description
1 apply()
It is an abstract method. It will commit your changes back from
editor to the sharedPreference object you are calling
2 clear()
It will remove all values from the editor
3 remove(String key)
It will remove the value whose key has been passed as a
parameter
4 putLong(String key, long value)
It will save a long value in a preference editor
In Game applications, Every time the user logs in to the application user
should be able to see the username, the last level he was in coupled with
.the high score that user has made. This is an example of persistent data
storage.
• Also, the application has to maintain user settings preferences, if the
user has turned on/off the music of the game or notifications.
•But when it comes to storing of large data then shared preference is not the
right choice. It fails to store large data.
• Do not opt for shared preferences to store Images, videos, Audio files,
large text files, spreadsheets or presentations.
Advantages of Shared Preferences
• It works on the key-value pair basis. Simply provide the key and get
corresponding value.
• Just a few lines of code required to manipulate data.
• Data is private to the corresponding application.
• It is useful to store user preferences.
• When needed, data can be shared among applications.
• Reading and writing data is easy and fast
•Unless the application is uninstalled or data is cleared from settings, data persists
in the application.
➢By internal storage files can be saved directly on the device's internal
memory.
➢By default, files saved to the internal storage are accessible to their
application, other applications can not access them.
➢When the user uninstalls the application, these files are removed.
➢To create and save a private file to the internal storage:
❖Call openFileOutput () with the file name and the operating
mode. This returns a FileOutputStream.
❖Write on file with the write ().
❖Close the stream with close ().
When the data is larger in amount or the data type is not primitive, the data is stored in
the device storage.
Internal storage is a built-in-non-volatile memory which is always available on the
device.
• The internal storage directory is private to the application and the data cannot be
accessed by other applications.
• Moreover, text and binary data like images can be stored in device's internal
memory.
• The data saved in the internal storage of the device is removed as soon as the
application is uninstalled from the device.
• File class and its various methods are used to store and retrieve the data in internal
file storage.
• Advantages of internal file storage
• Data access is private to the application.
• Internal storage is always available on the device.
• Disadvantages of internal file storage
• Uninstalling the application removes data internal storage.
• Internal storage cannot store a large amount of data.
Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
b). External storage
➢To access the database using the SQLite Open Helper, call
getWritableDatabase or getReadableDatabase to open and obtain a
writable or read-only instance of the underlying database, respectively.
4). Opening and Creating
Database without the SQLiteOpenHelper
➢In order to manage creation, opening and version control of
databases directly, openOrCreateDatabase method is used to create
the database itself :
SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME,
context.MODE_PRIVATE, null);
• Using raw query method - These are simple SQL queries similar to other
databases like MySql, Sql Server etc . In this case user will have to write
query as text and passed the query string in
• rawQuery(String sql ,String [] selectionArgs) or
• execSQL(String sql,Object [] bindArgs) method to perform operations.
mydatabase.execSQL("INSERT INTO testtable
values(‘admin','admin');");
➢To delete a row, simply call the delete method on a database, specifying
the table name and a where clause that returns the rows you want to
delete.
➢Delete function is available in SQLiteDatabase class.
➢public int delete(String tableName, String whereClause, String []
whereArgs)
➢Here whereClause is optional, passing null will delete all rows in
table.
➢Delete function will return number of affected row if whereClause
passed, otherwise will return 0.
To delete an Item
public void deleteltem(Item item)
{
SQLiteDatabase db = getWritableDatabase();
String whereClause = "id=?";
String whereArgs[] = {item.id.toString()};
db.delete("Items"•
, whereClause, whereArgs);
}
To replace rows in table –
SqliteDatabase db = getDatabase();
db.replace(tablename, null, contentValues);
To perform a query
SqliteDatabase db = getDatabase();
Cursor res = db.query(tablename, columnname, selectionclause,
selectionargs, groupby, having, orderby);
SQLITE AND DATABASE CENTRIC DATA MODEL FOR ANDROID
An architecture pattern gives modularity to the project. It makes the task easy for
developers to maintain the software and to expand the features of the application in the
future.
Model—View—Controller(MVC) Pattern is one of the architecture pattern in
Android.
The MVC pattern suggests splitting the code into 3 components. While creating the
class/file of the application, the developer must categorize it into one of the following
three layers:
Model: This component stores the application data. It has no knowledge about the
interface. The model is responsible for handling the domain logic(real-world business
rules) and communication with the database and network layers.
View: It is the UI(User Interface) layer that holds components
that are visible on the screen. Moreover, it provides the
visualization of the data stored in the Model and offers interaction
to the user.
Controller: This component establishes the relationship between
the View and the Model. It contains the core application logic
and gets informed of the user’s behaviour and updates the Model
as per the need.
Database - Helper class
For managing all the operations related to the database and for
version management, a helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and
update of the database.
Syntax
public class DBHelper extends SQLiteOpenHelper {
public DBHelper()
{
super(context, DATABASE_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db){}
public void onUpgrgde(SQLiteDatabase database, int oldVersion,
int newVersion){}
Android Database Classes
Java classes that are responsible for providing access to the SQLite functions
-
1. SQLite Database: This is the Android's Java interface to its relational
database, SQLite. It also supports an SQL or Structured Query Language
implementation which is rich enough to handle any requirement for mobile
application.