Chapter 4 (1)
Chapter 4 (1)
Method Description
getPreferences() For activity level preferences and each activity will have its own
preference file and by default, this method retrieves a default shared
preference file that belongs to the activity.
getSharedPreferences() To get the values from multiple shared preference files by passing
the name as a parameter to identify the file. We can call this from
any Context in our app.
To initialize the Shared Preferences in our application.
If we are using single shared preference file for activity, then we need to initialize the
SharedPreferences object by using getPreferences() method like as shown below.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
If we are using multiple shared preference files, then we need to initialize the SharedPreferences
object by using the getSharedPreferences() method like as shown below.
SharedPreferences sharedPref = getSharedPreferences("filename1",Context.MODE_PRIVATE);
Here, the name “filename1” is the preference file, which wants to read the values based on our
requirements and the context mode MODE_PRIVATE, will make sure that the file can be accessed
only within our application.
Mode & description
MODE_APPEND
This will append the new preferences with the already
existing preferences
MODE_ENABLE_WRITE_AHEAD_L
OGGING Database open flag. When it is set , it would enable write
ahead logging by default
MODE_MULTI_PROCESS
This method will check for modification of preferences
even if the sharedpreference instance has already been
loaded
MODE_PRIVATE
By setting this mode, the file can only be accessed using
calling application
MODE_WORLD_READABLE
This mode allow other application to read the preferences
MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences
Write to Shared Preferences
To store data in a shared preference file, we need an editor to edit and save the changes in the
SharedPreferences object.
Following is the code snippet to store the data in shared preference file using an editor.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("keyname",true);
editor.putString("keyname","string value");
editor.putInt("keyname","int value");
editor.putFloat("keyname","float value");
editor.putLong("keyname","long value");
editor.commit();
We created a SharedPreferences.Editor by calling the edit() method of SharedPreferences object. We
added a primitive data type values such as integer, float, long, string and Boolean by passing the keys and
values to the methods putInt(), putString(), etc. based on our requirements.
After that, to save all the changes we are calling commit() method.
Read from Shared Preferences
To read or retrieve values from the Shared Preferences file, we need to call methods such
as getInt(), getString(), etc. by providing the key for the value which we want to get like as shown
below.
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
pref.getString("keyname",null);
pref.getInt("keyname",0);
pref.getFloat("keyname",0);
pref.getBoolean("keyname",true);
pref.getLong("keyname",0);
We are getting the values from shared preferences using a methods such as getInt(), getFloat(), etc.
by providing the key for the value which we want to get.
Deleting from Shared Preferences
To delete values from the Shared Preferences file, we need to call remove() method by providing
the key for the value which we want to delete like as shown below.
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.remove("keyname");
editor.commit();
We are deleting the values from shared preferences using a method called remove() by providing
the key for the value which we want to delete and committing the changes to shared preferences
file using commit() method.
Clearing from Shared Preferences
We can clear all the data from Shared Preferences file using a clear() method like as shown
below.
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
We are clearing all the values from shared preferences using a method called clear() and
committing the changes to shared preferences file using commit() method.
4.2. Using the Internal Storage
Internal Storage is useful to store the data files locally on the device’s internal memory using
a FileOutputStream object.
After storing the data files in device internal storage, we can read the data file from the device
using a FileInputStream object.
The data files saved in the internal are managed by an android framework and it can be
accessed anywhere within the app to read or write data into the file, but it’s not possible to
access the file from any other app so it’s secured.
When the user uninstalls the app, automatically these data files will be removed from the
device internal storage.
Write a File to Internal Storage
By using the android FileOutputStream object openFileOutput method, we can easily create
and write data to a file in a device’s internal storage.
String FILENAME = "user_details";
String name = “ALEX";
FileOutputStream fstream = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fstream.write(name.getBytes());
fstream.close();
Method Description
getChannel() It returns the unique FileChannel object associated with this file output
stream.
getFD() It returns the file descriptor which is associated with the stream.
write(byte[] b, int off, int It writes len bytes from the specified byte array starting at offset off to
len) the file output stream.
Read a File from Internal Storage
To read a file from internal storage:
String FILENAME = "user_details";
FileInputStream fstream = openFileInput(FILENAME);
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
fstream.close();
Method Description
getChannel() It returns the unique FileChannel object associated with this file output stream.
getFD() It returns the file descriptor which is associated with the stream.
read(byte[] b, int off, int len) It reads len bytes of data from the specified file input stream into an array of
bytes.
4.3. Using the External Storage
External Storage is useful to store the data files publically on the shared external storage using
the FileOutputStream object.
After storing the data files on external storage, we can read the data file from external storage
media using a FileInputStream object.
The data files saved in external storage are word-readable and can be modified by the user when
they enable USB mass storage to transfer files on a computer.
Grant Access to External Storage
To read or write files on the external storage, our app must acquire the
WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE system permissions.
For that, we need to add the following permissions in the android manifest file like as shown below.
<manifest>
....
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
....
</manifest>
Checking External Storage Availability
Before we do any work with external storage, first we need to check whether the media is available or not
by calling getExternalStorageState().
The media might be mounted to a computer, missing, read-only or in some other state. To get the media
status, we need to write the code like as shown below.
boolean Available= false;
boolean Readable= false;
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
// Both Read and write operations available
Available= true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
// Only Read operation available
Available= true;
Readable= true;
} else {
// SD card not mounted
Available = false;
}
We used getExternalStorageState() method to know the status of media mounted to a computer, such as
missing, read-only or in some other state.
Cont..
By using getExternalStoragePublishDirectory() method we can access the files from appropriate
public directory by passing the type of directory we want, such as DIRECTORY_MUSIC,
DIRECTORY_PICTURES, DIRECTORY_RINGTONES, etc. based on our requirements.
If we save our files to corresponding media-type public directory, the system's media scanner can
properly categorize our files in the system.
Following is the example to create a directory for a new photo album in the public pictures directory.
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
In case, if we are handling the files that are not intended for other apps to use, then we should use a
private storage directory on the external storage by calling getExternalFilesDir().
Write a File to External Storage
By using android FileOutputStream object and getExternalStoragePublicDirectory method,
we can easily create and write data to the file in external storage public folders.
Following is the code snippet to create and write a public file in the device Downloads folder.
String FILENAME = "user_details";
String name = “CCI";
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DO
WNLOADS);
File myFile = new File(folder, FILENAME);
FileOutputStream fstream = new FileOutputStream(myFile);
fstream.write(name.getBytes());
fstream.close();
If you observe above code, we are creating and writing a file in device public Downloads folder
by using getExternalStoragePublicDirectory method.
We used write() method to write the data in file and used close() method to close the stream.
Read a File from External Storage
By using the android FileInputStream object and getExternalStoragePublicDirectory method,
we can easily read the file from external storage.
To read data from a file that is in the downloads folder.
String FILENAME = "user_details";
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFile = new File(folder, FILENAME);
FileInputStream fstream = new FileInputStream(myFile);
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
fstream.close();
Reading a file from device Downloads folder storage by using FileInputStream object
getExternalStoragePublicDirectory method with file name.
We used read() method to read one character at a time from the file and used close() method to
close the stream.
4.4. Android SQLite Database
SQLite is an open-source lightweight relational database management system (RDBMS) to
perform database operations, such as storing, updating, retrieving data from the database.
In case, if we want to deal with large amounts of data, then SQLite database is the preferable
option to store and maintain the data in a structured format.
By default, Android comes with built-in SQLite Database support so we don’t need to do any
configurations.
Save the files on the device’s internal storage, Android stores our database in a private disk
space that’s associated with our application and the data is secure, because by default this area is
not accessible to other applications.
The package android.database.sqlite contains all the required APIs to use an SQLite database
in our android applications.
Now we will see how to create a database and required tables in SQLite and perform CRUD
(insert, update, delete and select) operations in android applications.
Create Database and Tables using SQLite Helper
In android, by using SQLiteOpenHelper class we can easily create the required database and
tables for our application.
To use SQLiteOpenHelper, we need to create a subclass that overrides the onCreate() and
onUpgrade() call-back methods.
Creating the database and tables using the SQLiteOpenHelper class in our android application.
public class DbHandler extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = “CCI";
private static final String TABLE_Users = “Student";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_LOC = "location";
private static final String KEY_DESG = "designation";
public DbHandler(Context context){
super(context,DB_NAME, null, DB_VERSION);
}
Cont..
@Override
public void onCreate(SQLiteDatabase db){
String CREATE_TABLE = "CREATE TABLE " + TABLE_Users + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ KEY_LOC + " TEXT,"
+ KEY_DESG + " TEXT"+ ")";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
// Drop older table if exist
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Users);
// Create tables again
onCreate(db);
}
}
We are creating database “CCI” and table “Student” using SQLiteOpenHelper class by
overriding onCreate and onUpgrade methods.
Cont..
Method Description
onCreate() This method is called only once throughout the application after the database is
created and the table creation statements can be written in this method.
onUpgrade() This method is called whenever there is an updation in the database like modifying
the table structure, adding constraints to the database, etc.
we can update the data in the SQLite database using an update() method in android applications.
To update the data in the SQLite database using an update() method in the android application.
//Get the Data Repository in write mode
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cVals = new ContentValues();
cVals.put(KEY_LOC, location);
cVals.put(KEY_DESG, designation);
int count = db.update(TABLE_Users, cVals, KEY_ID+" = ?",new String[]{String.valueOf(id)});
Updating the details using update() method based on our requirements
Delete Data from SQLite Database
we can delete data from the SQLite database using the delete() method in android applications.
To delete the data from the SQLite database using the delete() method in the android application.
//Get the Data Repository in write mode
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_Users, KEY_ID+" = ?",new String[]{String.valueOf(userid)});
Deleting the details using delete() method based on our requirements.
Synchronization and Replication of Mobile Data
Data synchronization is a method of establishing consistency among data from a data source
to the target data storage and vice versa.
In data synchronization, we have to keep multiple copies of a dataset in coherence with one
another to maintain the data integrity.
Data synchronization provides the continuous harmonization of the data over time. This is the
basic fundamental concept used in a wide variety of applications, including file synchronization
and mobile device synchronization, e.g., PDAs. It is also used in encryption for synchronizing
Public Key Servers.
Data synchronization ensures accurate, secure, compliant data and successful team and
customer experiences. It assures congruence between each source of data and its different
endpoints.
Cont..
Data synchronization is important and required in mobile computing because it checks the differences between
two data containers or data sources and data receivers to restrict the unnecessary transfer of data that already
resides in both data sources.
The data synchronization process typically updates both data sources by transferring only additions, changes,
and deletions.
The following are the reasons why data synchronization is required in Mobile computing:
Data synchronization is required between the mobile devices and their service provider.
It is also required between the device and personal area computer and nearby wireless access points (in Wi-
Fi connection) and other nearby devices.
It is used to establish consistency among data from a data source to the target data storage and vice versa.
Example of Data Synchronization
Working with a Content Provider
Content Providers are a very important component that serves the purpose of a relational database to store the
data of applications.
The role of the content provider in the android system is like a central repository in which data of the
applications are stored, and it facilitates other applications to securely access and modifies that data based on
the user requirements.
Android system allows the content provider to store the application data in several ways.
Users can manage to store the application data like images, audio, videos, and personal contact information
by storing them in SQLite Database, in files, or even on a network.
In order to share the data, content providers have certain permissions that are used to grant or restrict the
rights to other applications to interfere with the data.
Content URI
Content URI (Uniform Resource Identifier) is the key concept of Content providers. To
access the data from a content provider, URI is used as a query string.
Structure of a Content URI: content://authority/optionalPath/optionalID
Details of different parts of Content URI:
content:// – Mandatory part of the URI as it represents that the given URI is a Content URI.
authority – Signifies the name of the content provider like contacts, browser, etc. This part must be
unique for every content provider.
optionalPath – Specifies the type of data provided by the content provider. It is essential as this part helps
content providers to support different types of data that are not related to each other like audio and video
files.
optionalID – It is a numeric value that is used when there is a need to access a particular record.
If an ID is mentioned in a URI then it is an id-based URI otherwise a directory-based URI.
Operations in Content Provider
Four fundamental operations are possible in Content Provider: Create, Read, Update, and Delete.
Create: Operation to create data in a content provider.
Read: Used to fetch data from a content provider.
Update: To modify existing data.
Delete: To remove existing data from the storage.
Working of the Content Provider UI components of android applications like Activity and Fragments
use an object CursorLoader to send query requests to ContentResolver. The ContentResolver object
sends requests (like create, read, update, and delete) to the ContentProvider as a client. After receiving
a request, Content Provider process it and returns the desired result. Below is a diagram to represent
these processes in pictorial form.
Creating a Content Provider
Following are the steps which are essential to follow in order to create a Content Provider:
Create a class in the same directory where the that MainActivity file resides and this class must
extend the ContentProvider base class.
To access the content, define a content provider URI address.
Create a database to store the application data.
Implement the six abstract methods of ContentProvider class.
Register the content provider in AndroidManifest.xml file using <provider> tag.
THANK YOU!