0% found this document useful (0 votes)
18 views32 pages

Chapter 4

Smart

Uploaded by

amentiabraham674
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views32 pages

Chapter 4

Smart

Uploaded by

amentiabraham674
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

CHAPTER 4:

Storing and Retrieving Data


COMPILED BY CHALEW Z.(MSC) 1
INTRODUCTION
 Android provides several options for you to save your app data. The solution you choose
depends on your specific needs, such as
 How much space your data requires,
 What kind of data you need to store, and
 Whether the data should be private to your app or accessible to other apps and the
user.
 Data storage options available on Android:
 Internal file storage: Store app-private files on the device file system.
 External file storage: Store files on the shared external file system. This is usually for
shared user files, such as photos.
 Shared preferences: Store private primitive data in key-value pairs.
 Databases: Store structured data in a private database.
 Network Connection: Store data on the web with your own network server
COMPILED BY CHALEW Z.(MSC) 2
Cont..

Attention: Except for some types of files on external storage, all


these options are intended for app-private data the data is not
naturally accessible to other apps. If you want to share files with other
apps, you should use the FileProvider API.

COMPILED BY CHALEW Z.(MSC) 3


Internal storage
 By default, files saved to the internal storage are private to your app, and other apps
cannot access them (nor can the user, unless they have root access).

 This makes internal storage a good place for internal app data that the user doesn't
need to directly access.

 The system provides a private directory on the file system for each app where you can
organize any files your app needs.

 When the user uninstalls your app, the files saved on the internal storage are removed.

 Because of this behavior, you should not use internal storage to save anything the user
expects to persist independently of your app.
COMPILED BY CHALEW Z.(MSC) 4
Internal cache files
 If you had like to keep some data temporarily, rather than store it persistently, you should
use the special cache directory to save the data.

 Each app has a private cache directory specifically for these kinds of files.

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

 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 app, these files are removed.

COMPILED BY CHALEW Z.(MSC) 5


Writing file
 In order to use internal storage to write some data in the file, call the openFileOutput()
method with the name of the file and the mode.

 The mode could be private , public

 Its syntax is given below

FileOutputStream fOut = openFileOutput("file_name_here", MODE_PRIVATE);


 The method openFileOutput() returns an instance of FileOutputStream. So you receive
it in the object of FileInputStream. After that you can call write method to write data on
the file.

 Its syntax is given below String str = "data";

fOut.write(str.getBytes());
fOut.close();
COMPILED BY CHALEW Z.(MSC) 6
Reading file
 In order to read from the file you just created , call the openFileInput() method with the name
of the file. It returns an instance of FileInputStream.

 Its syntax is given below

FileInputStream fin = openFileInput(file);

 After that, you can call read method to read one character at a time from the file and then you
can print it. Its syntax is given below
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);}// temp contains all the data of the file.
fin.close();
COMPILED BY CHALEW Z.(MSC) 7
External storage
 Every Android device supports a shared "external storage" space that you can use to save files.
This space is called external.

 It is a storage space that users can mount to a computer as an external storage device, and it might
even be physically removable (such as an SD card).
 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.
 So before you attempt to access a file in external storage in your app, you should check for the
availability of the external storage directories as well as the files you are trying to access.
 Most often, you should use external storage for user data that should be accessible to other apps
and saved even if the user uninstalls your app, such as captured photos or downloaded files.
 The system provides standard public directories for these kinds of files, so the user has one
location for all their photos, ringtones, music, and such.

COMPILED BY CHALEW Z.(MSC) 8


Shared preferences
 If you don't need to store a lot of data and it doesn't require structure, you should use
SharedPreferences.

 The SharedPreferences APIs allow you to read and write persistent key-value pairs of primitive data
types: booleans, floats, ints, longs, and strings.

 SharedPreferences used to store small entries/data

 The key-value pairs are written to XML files that persist across user sessions, even if your app is killed.

 You can manually specify a name for the file or use per-activity files to save your data.

 The API name "shared preferences" is a bit misleading because the API is not strictly for saving "user
preferences," such as what ringtone a user has chosen.

 You can use SharedPreferences to save any kind of simple data, such as the user's high score.
COMPILED BY CHALEW Z.(MSC) 9
Shared preferences
 In order to use shared preferences, you have to call a method getSharedPreferences() that
returns a SharedPreference instance pointing to the file that contains the values of
preferences.

 General Syntax:

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,


Context.MODE_PRIVATE);

 The first parameter is the key and the second parameter is the MODE.

COMPILED BY CHALEW Z.(MSC) 10


Example: MainActivity.java. activiy_main.xml.
public class MainActivity extends AppCompatActivity {
EditText text; <EditText
Button b1; android:layout_width="wrap_content"
public static final String MyPreferences = "MyPr" ; android:layout_height="wrap_content"
public static final String Name = "nameKey"; android:id="@+id/editText"
SharedPreferences sharedpreferences;
android:layout_marginTop="67dp"
@Override protected void onCreate(Bundle savedInstanceState) {
android:hint="Name"
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); android:layout_alignParentRight="true"
text=(EditText)findViewById(R.id.editText); android:layout_alignParentEnd="true"
b1=(Button)findViewById(R.id.button); android:layout_alignParentLeft="true"
sharedpreferences = getSharedPreferences(MyPreferences, android:layout_alignParentStart="true"
Context.MODE_PRIVATE);
<Button android:layout_width="wrap_content"
b1.setOnClickListener(new View.OnClickListener() {
android:layout_height="wrap_content"
@Override public void onClick(View v) {
String n = text.getText().toString(); android:text="Save" android:id="@+id/button"
SharedPreferences.Editor editor = sharedpreferences.edit(); android:layout_centerHorizontal="true"
editor.putString(Name, n); android:layout_marginTop="50dp" />
editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
} }); } } COMPILED BY CHALEW Z.(MSC) 11
Database
What is a database?

 A database is an organized collection of data that can be easily accessed, managed, and updated.

 It used to store information in a structured format, allowing for efficient retrieval and
manipulation of data.

 They are fundamental in various applications, from small websites to large enterprise systems.

COMPILED BY CHALEW Z.(MSC) 12


Cont…
Relational Database: is a type of database that organizes data into tables, which are
structured in a way that allows for easy access and management of related data points

Here are key features and concepts associated with relational databases:
 Tables: Data is stored in tables, which consist of rows and columns.
 Rows: Each row in a table represents a single record or entry.
 Columns: Each column in a table represents a specific attribute or field of the record.
 Relationships: Data in different tables can be related to one another through foreign keys, which link
tables.
 Structured Query Language (SQL): Relational databases typically use SQL, a standardized
programming language, to define, manipulate, and query data.
 SQL allows users to perform operations such as: SELECT, INSERT, UPDATE, and DELETE

COMPILED BY CHALEW Z.(MSC) 13


Cont..
Why use a database?

 Powerful: can search, filter, combine data from many sources

 Fast: can search/filter a database very quickly compared to a file

 Big: scale well up to very large data sizes

 Safe: built-in mechanisms for failure recovery (transactions)

 Multi-user: concurrency features let many users view/edit data at same time

 Abstract: layer of abstraction between stored data and app(s)

 Common syntax: database programs use same SQL commands


COMPILED BY CHALEW Z.(MSC) 14
Cont..
Some database software
 Oracle
 Microsoft
 SQLServer(powerful)
 Access(simple)
 PostgreSQL
 powerful/complex free open-source database system
 MySQL: simple free open-source database system
 SQLite: transportable, lightweight free open-source database system

COMPILED BY CHALEW Z.(MSC) 15


Android includes SQLite
 Android provides full support for SQLite databases.

 SQLite is a library, runs in the app’s process

 SQLite is an Open Source Database which is embedded into Android.

 SQLite supports standard relational database features like SQL syntax, transactions and
prepared statements.

COMPILED BY CHALEW Z.(MSC) 16


Android includes SQLite
 In addition it requires only little memory at runtime (approx. 250 KByte).

 SQLite supports the data types TEXT (similar to String in Java),

INTEGER (similar to long in Java) and

REAL (similar to double in Java).

 All other types must be converted into one of these fields before saving them in the database.

COMPILED BY CHALEW Z.(MSC) 17


Cont..
 SQLite in Android

 SQLite is available on every Android device.

 Using an SQLite database in Android does not require any database setup or administration.

 You only have to define the SQL statements for creating and updating the database.

 Afterwards the database is automatically managed for you by the Android platform.

 Access to an SQLite database involves accessing the filesystem.

 If your application creates a database, this database is by default saved in the directory like

DATA/data/APP_NAME/databases/FILENAME.

COMPILED BY CHALEW Z.(MSC) 18


Why SQLite?
 SQLite does not require a separate server process or system to operate (serverless).

 SQLite comes with zero-configuration, which means no setup or administration needed.

 A complete SQLite database is stored in a single cross-platform disk file.

 SQLite is very small and light weight, less than 400KiB fully configured or less than 250KiB with
optional features omitted.

 SQLite is self-contained, which means no external dependencies.

 SQLite supports most of the query language features found in SQL92 (SQL2) standard.

 SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32, WinCE, WinRT)

COMPILED BY CHALEW Z.(MSC) 19


Cont..
 Packages in SQLite
The package android.database contains all general classes for working with databases.
 android.database.sqlite contains the SQLite specific classes.
SQLiteOpenHelper
 To create and upgrade a database in your Android application you usually subclass
SQLiteOpenHelper.
 In the constructor of your subclass you call the super() method of SQLiteOpenHelper,
specifying the database name and the current database version.
 In this class you need to override the onCreate() and onUpgrade() methods.
 onCreate() is called by the framework, if the database does not exists.
 onUpgrade() is called, if the database version is increased in your application code.
This method allows you to update the database schema.
COMPILED BY CHALEW Z.(MSC) 20
Cont..
 Packages in SQLite

Both methods receive an SQLiteDatabase object as parameter which represents the database.

SQLiteOpenHelper provides the methods getReadableDatabase() and


getWriteableDatabase() to get access to an SQLiteDatabase object; either in read or write
mode.

 SQLiteDatabase

SQLiteDatabase is the base class for working with a SQLite database in android and provides
methods to open, query, update and close the database.

More specifically SQLiteDatabase provides the insert() , update() and delete() methods.

In addition it provides the execSQL() method, which allows to execute an SQL statement
COMPILED BY CHALEW Z.(MSC) 21
The object ContentValues allows to define key/values. Cont..
 The "key" represents the table column identifier and

 the "value" represents the content for the table record in this column.

 ContentValues can be used for inserts and updates of database entries.

Queries can be created via the rawQuery() and query() methods or via the
SQLiteQueryBuilder class .

rawQuery() directly accepts an SQL select statement as input.

query() provides a structured interface for specifying the SQL query.

SQLiteQueryBuilder is a convenience class that helps to build SQL queries.

COMPILED BY CHALEW Z.(MSC) 22


rawQuery() Example Cont..
The following gives an example of a rawQuery() call.

query() Example

The following gives an example of a query() call

COMPILED BY CHALEW Z.(MSC) 23


Cont..

COMPILED BY CHALEW Z.(MSC) 24


Cursor
Cont..
A query returns a Cursor object.
A Cursor represents the result of a query and basically points to one row of the query
result.
This way Android can buffer the query results efficiently; as it does not have to load all
data into memory.
To get the number of elements of the resulting query use the getCount() method.
To move between individual data rows, you can use the moveToFirst() and
moveToNext() methods.
The isAfterLast() method allows to check if the end of the query result has been
reached.
Cursor provides typed get*() methods, e.g. getLong(columnIndex) ,
getString(columnIndex) to access the column data for the current position of the
result.
The "columnIndex" is the number of the column you are accessing. COMPILED BY CHALEW Z.(MSC) 25
Synchronization and Replication of Mobile Data
Data Synchronization in Mobile Computing
 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.

COMPILED BY CHALEW Z.(MSC) 26


Cont..
Synchronization in mobile computing systems

Process of maintaining the availability of data generated from the source and
maintaining consistency.

A consistent copy of data is a copy which may not be identical to the present data
record at the data generating source, but must satisfy all the required functions
and domain dependent specific rules .

The domain specific rules are in terms of resolution, precision, data format,
and time interval permitted for replication.

COMPILED BY CHALEW Z.(MSC) 27


The requirement of Data Synchronization systems 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.

COMPILED BY CHALEW Z.(MSC) 28


Cont..
Let us consider a PC is associated with mobile device and this computer connected to the
internet which download applications and large files.
Now consider the data at the computer is modified at some instant, the disseminated
data at the server has changed at another instant, the data at mobile device is also
changed at another instant the changes are take place at one of the three ends at
different instants.
There be a need to synchronize the data at three ends.
Data replication may done by copying the data from
 one place to another place
 one place to many other places
 many other places to many other places.
 The replicated data may be full copy or an partial copy

COMPILED BY CHALEW Z.(MSC) 29


Cont..
Data Replication in mobile computing systems

Data Replication in mobile computing means the sharing of information to ensure data
consistency between software and hardware resources connected via the internet, to
improve reliability, availability, fault-tolerance, and accessibility of data.

In simpler terms, data replication is the process of storing different copies of the
database at two or more sites in order to improve data availability in less time and at a
cheaper cost.

Data replication in mobile computing is a popular fault tolerance technique for


distributed databases.

COMPILED BY CHALEW Z.(MSC) 30


Cont..
Data replication is performed with the purpose of

Increasing the availability of data.

Speeding up the query evaluation.

COMPILED BY CHALEW Z.(MSC) 31


End,
Any question?

COMPILED BY CHALEW Z.(MSC) 32

You might also like