Chapter 4 Storing and Retrieving Data

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 22

CHAPTER 4

Storing and Retrieving Data 1


4.1. INTRODUCTION

 Android provides several options for you to save persistent application data.

 The solution you choose depends on your specific needs, such as whether the data should

be private to your application or accessible to other applications (and the user) and how
much space your data requires.

2
INTRODUCTION…
 The data storage options are the following:
 Shared Preferences

Store private primitive data in key-value pairs.


 Internal Storage

Store private data on the device memory.


 External Storage

Store public data on the shared external storage.


 SQLite Databases

Store structured data in a private database.


 Network Connection

Store data on the web with your own network server.

3
USING SHARED PREFERENCES
The Shared Preferences class provides a general framework that allows you to save and retrieve persistent key-value pairs

of primitive data types.

You can use Shared Preferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist

across user sessions (even if your application is killed).

To write values:

1. Call edit() to get a SharedPreferences.Editor.

2. Add values with methods such as putBoolean()and putString().

3. Commit the new values with commit()

To read values, use SharedPreferences methods such as getBoolean()and getString().

4
USING THE INTERNAL STORAGE
You can save files directly on the device’s internal storage. By default, files saved to the internal storage are private

to your application and other applications cannot access them (nor can the user).
When the user uninstalls your application, these files are removed.

To create and write a private file to the internal storage:

1. Call openFileOutput()with the name of the file and the operating mode. This returns a FileOutputStream.

2. Write to the file with write().

3. Close the stream with close().

To read a file from internal storage:

1. Call openFileInput()and pass it the name of the file to read. This returns a FileInputStream.

2. Read bytes from the file with read().

3. Then close the stream with close().


5
SAVING CACHE FILES

If you’d like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that

represents the internal directory where your application should save temporary cache files.

When the device is low on internal storage space, Android may delete these cache files to recover space.

However, you should not rely on the system to clean up these files for you.

You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB.

When the user uninstalls your application, these files are removed.

6
USING THE EXTERNAL STORAGE

Every Android-compatible device supports a shared “external storage” that you can use to

save files. This can be a removable storage media (such as an SD card) or an internal (non-
removable) storage.
Files saved to the external storage are world-readable and can be modified by the user when

they enable USB mass storage to transfer files on a computer.


Caution: External files can disappear if the user mounts the external storage on a computer or

removes the media, and there’s no security enforced upon files you save to the external storage.
All applications can read and write files placed on the external storage and the user can

remove them.

7
USING A NETWORK CONNECTION

You can use the network (when it’s available) to store and retrieve data on your own web-based

services. To do network operations, use classes in the following packages:


 java.net.*

 android.net.*

8
4.2. SYNCHRONIZATION AND REPLICATION OF MOBILE
DATA
 Data synchronization is a method of establishing consistency(uniformity) 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 ensures accurate, secure, compliant data and successful team and
customer experiences.
 It assures similarity between each source of data and its different endpoints.
 As data comes in, it is cleaned, checked for errors, duplication, and consistency before being
put to use. Local synchronization involves devices and computers that are next to each other,
while remote synchronization takes place over a mobile network.
 Data must always be consistent throughout the data record.
 If data is modified in any way, changes must upgrade through every system in real-time to
avoid mistakes, prevent privacy cracks, and ensure that the most up-to-date data is the only
information available.
 Data synchronization ensures that all records are consistent, all the time.
9
4.2. SYNCHRONIZATION AND REPLICATION OF MOBILE DATA…
 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.

 Some example of Data Synchronization are given below

10
4.2. SYNCHRONIZATION AND REPLICATION OF MOBILE DATA…
 Suppose we have added a new popular ringtone to one of the servers of a mobile service provider, so

here, data synchronization means that all the service provider servers get identical sets of ringtones.

 All the devices connected to the server should be updated about the availability of the new data.

 The ringtone databases available to all the mobile phones include a copy of the title of that tone.

 Mobile devices use data for basic operation as well as personal information for apps, websites, and email.

 Updates to information generated by the user as well as the end target must be constant and secure.

 This synchronization process requires clean, consistent data for product and service competence, but also

for data governance issues like security and regulatory compliance.

11
4.3. WORKING WITH A CONTENT PROVIDER
 In Android, Content Providers are a very important component that serves (helps) 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. 12
4.3. WORKING WITH A CONTENT PROVIDER…

13
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. 14
OPERATIONS IN CONTENT PROVIDER

Four fundamental operations are possible in Content Provider


namely Create, Read, Update, and Delete. These operations are often termed as CRUD
operations.
 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.

15
WORKING OF THE CONTENT PROVIDER
 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

Examples of content provider


• Music playlist
• Calls logs
• Contact list
• Message threads
• Gallery application
• File managers

16
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 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.

17
CREATING A CONTENT PROVIDER
 Following are the six abstract methods and their description which are essential to override as the part

of Content Provider class:

 Abstract Method

 query(): A method that accepts arguments and fetches the data from the desired table. Data is retired

as a cursor object.

 insert(): To insert a new row in the database of the content provider. It returns the content URI of the

inserted row.

 update(): This method is used to update the fields of an existing row. It returns the number of rows

updated.

 delete(): This method is used to delete the existing rows. It returns the number of rows deleted.

 getType(): This method returns the Multipurpose Internet Mail Extension(MIME) type of data to the

given Content URI.

 onCreate(): As the content provider is created, the android system calls this method immediately to
18
initialize the provider.
CREATING A CONTENT PROVIDER…
 Example

 The primery purpose of a content provider is to serve as a central repository of

data where users can store and can fetch the data. The access of this repository is
given to other applications also but in a safe manner in order to serve the different
requirements of the user. The following are the steps involved in implementing a
content provider. In this content provider, the user can store the name of persons
and can fetch the stored data. Moreover, another application can also access the
stored data and can display the data.

19
CREATING A CONTENT PROVIDER…

Step 1: Create a new project


Strings.xml
1. Click on File, then New => New
Project. <resources>
2. Select language as Java. <string
3. Choose empty activity as a template name=”app_name”>Content_Provider_In_Android</string>
4. Select the minimum SDK as per your
<string name=”hintText”>Enter User Name</string>
need.
Step 2: Modify the strings.xml file <string name=”heading”>Content Provider In
 All the strings used in the activity are Android</string>
stored here
<string name=”insertButtontext”>Insert Data</string>

<string name=”loadButtonText”>Load Data</string>

</resources>

20
CREATING A CONTENT PROVIDER
Step 3: Creating the Content Provider class
1. Click on File, then New => Other => ContentProvider.
2. Name the ContentProvider
3. Define authority (it can be anything for example “com.demo.user.provider”)
4. Select Exported and Enabled option
5. Choose the language as Java
Step 4: Design the activity_main.xml layout

21
END
22

You might also like