You are on page 1of 21

UNIVERSITATEA TEHNICĂ “GH.

ASACHI” DIN IAŞI


FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

Data storage

2021
Data storage
Contents
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

1. Types of data storages


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

2. Shared Preferences

3. Internal Storage

4. External Storage

5. SQL Database
Data storage
1. Types of data storages
❖Android system provides many options for application developers for storing data.
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

❖Data can be stored in the following ways:

– With Shared preferences: Store private key-value pairs


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

– In Internal storage: Store application files in a private area that it's not accessible

to other applications

– In External storage: Store files in an area that it's accessible to other applications

and to the user

– In a SQL database: Store private data in a SQL database

❖Private data can be shared to other applications by a ContentProvider.

❖Private files can be shared to other applications by a FileProvider.


Data storage
2. Shared Preferences
❖SharedPreferences is a class for persistently storing and then reading pairs of key-value data
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

in the context of an application. Thus, the data is accessible only to the application that created

it. Android device stores each app’s Shared Preferences inside of an XML file in a private

directory.
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

❖An instance to SharedPreferences can be obtained in the following ways:

❖By calling getPreferences(MODE_PRIVATE), for obtaining an instance that has access

only to the data stored by that Activity.

❖By calling getSharedPreferences("Pref_Name", MODE_PRIVATE), where

“Pref_Name” is the identifier of the location where the data is be stored. Thus, in the

application, the data is visible to any Activity that obtained the instance to the

SharedPreferences for the same identifier.


Data storage
2. Shared Preferences
❖The first parameter is the key and the second parameter is the MODE. Apart from private
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

there are other modes available that are listed below:


Sr.No Mode & description
1 MODE_APPEND
This will append the new preferences with the already existing preferences
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

2 MODE_ENABLE_WRITE_AHEAD_LOGGING
Database open flag. When it is set , it would enable write ahead logging by default

3 MODE_MULTI_PROCESS
This method will check for modification of preferences even if the sharedpreference
instance has already been loaded

4 MODE_PRIVATE
By setting this mode, the file can only be accessed using calling application

5 MODE_WORLD_READABLE
This mode allow other application to read the preferences

6 MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences
Data storage
2. Shared Preferences
❖The key is of type String
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

❖The value can be of type int, long, boolean, float, String or String Set.

❖Example of storing a key with its value in the context of an Activity:


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

//Obtain an instance to Editor object. Editor object will allow


adding/modifying a value for key, deleting a key.
SharedPreferences.Editor sharedPrefEditor =
getPreferences(MODE_PRIVATE).edit();
//save the key-value pair
sharedPrefEditor.putString("keyName", "A value");
//commit the changes
sharedPrefEditor.commit();

❖Example of reading the stored value of a key in the context of an Activity:


//Obtain an instance to SharedPreferences object. This object will allow
reading of values based on a key.
SharedPreferences sharedPrefReader = getPreferences(MODE_PRIVATE);
//read the value stored for key "keyName"
String readValue = sharedPrefReader.getString("keyName", null);
Data storage
3. Internal storage
❖Files can be saved in Internal storage, in an area defined by the system for each
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

application, which is not accessible to other applications. The user can have access to that

files only with root permission.


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

❖ Example of writing data to a file that is saved private for that application in the Internal

storage:
//Function openFileOutput returns a FileOutputStream object to the file to
write.
//”aTextFile.txt” represents the name of the file
//Assigning Context.MODE_PRIVATE makes the file to be private for the
application
FileOutputStream fOutStream = openFileOutput("aTextFile.txt",
Context.MODE_PRIVATE);
//write the content to the file
fOutStream.write(content.getBytes());
//close the FileOutputStream object
fOutStream.close();
Data storage
3. Internal storage
❖Example of reading from file from the Internal storage:
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

//Obtain a fileInputStream to the file


FileInputStream fInStream = openFileInput("aTextFile.txt");
if(null != fInStream)
{
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

//Obtain an inputStreamReader from the inputStream


InputStreamReader fInputStreamReader = new
InputStreamReader(fInStream);
//obtain a bufferreader
BufferedReader buffReader = new
BufferedReader(fInputStreamReader);
//read line by line the content of the file
String newLine = buffReader.readLine();
while (newLine != null) {
content.append(newLine).append('\n');
newLine = buffReader.readLine();
}
}
Data storage
4. External storage
❖The External storage is useful for saving files that can be shared with other applications
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

or can be accessed by the user.

❖External storage is typically represented by a SDCard and it's available at the /sdcard
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

path.

❖The following types of external files can be created:

– Public files: Files that should be accessible to other apps and to the user. These

files will not be deleted when the application is uninstalled.

– Private files: These files are stored in application’s specific directory and are

accessed by Context.getExternalFilesDir() function. They will be deleted when the

application is uninstalled or will be unavailable if the storage is removed.


Data storage
4. External storage
❖The following permissions are shall be added to AndroidManifest.xml for granting access
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

to the External storage:

– READ_EXTERNAL_STORAGE: For allowing application to access in read mode the


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

external storage

– WRITE_EXTERNAL_STORAGE: For allowing application to access in write mode

the external storage.

❖Example:
<manifest ...>
...
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</manifest>
Data storage
4. External storage
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

❖In order to check if the external storage is available for reading and writing, the

following verification should be done:


public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}

In order to check if the external storage is available for reading, the following verification

should be done:
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
Data storage
External Storage
❖Example of writing a private file to the External storage:
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

if(isExternalStorageWritable()) {
//getExternalFilesDir returns the allocated dir for the app
for a specific type of files
File fileNote = new
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

File(getApplicationContext().getExternalFilesDir(Environment.DIREC
TORY_DOWNLOADS), "myExternalFile.txt");
//obtain a FileOutputStream for the file
FileOutputStream fOutStream = new FileOutputStream(fileNote);
//write the content to the file
fOutStream.write(content.getBytes());
//close the FileOutputStream object
fOutStream.close();
}
else
{
System.out.println("Storage is not writable");
}
Data storage
4. External Storage
❖Example of reading a private file from the External storage:
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

if(isExternalStorageReadable()) {
//Obtain a inputStream to the file
File fileNote = new
File(getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNL
OADS), "myExternalFile.txt");
FileInputStream fInStream = new FileInputStream(fileNote);
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

if (null != fInStream) {
//Obtain an inputStreamReader from the inputStream
InputStreamReader fInputStreamReader = new
InputStreamReader(fInStream);
//obtain a bufferreader
BufferedReader buffReader = new BufferedReader(fInputStreamReader);
//read line by line the content of the file
String newLine = buffReader.readLine();
while (newLine != null) {
content.append(newLine).append('\n');
newLine = buffReader.readLine();
}
}
}
else {
System.out.println("Storage is not readable");
}
Data storage
5. SQL Database
❖Android allows storing data in an SQL database, which is the SQLite database.
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

❖For accessing the SQLite database, it’s needed to create a class extends the class

SQLiteOpenHelper and to implement its abstract methods, onCreate() and onUpdate().


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

❖Example of such class, which creates a database that has a table with two columns:
public class LoginDB extends SQLiteOpenHelper {
//The name of the database file
private static final String LOGIN_DATABASE_NAME = "login.db";
//the name of the table
private static final String TABLE_NAME = "accounts";
//the name of the user column in the table
private static final String FIELD_USER = "user";
//the name of the password column in the table
private static final String FIELD_PASSWORD = "password";
//the version of the database
private static final int DATABASE_VERSION = 1;

public LoginDB(@Nullable Context context) {


//Call the constructor of the SQLiteOpenHelper class
super(context, LOGIN_DATABASE_NAME, null, DATABASE_VERSION);
}
Data storage
5. SQL Database
❖The onCreate() method of the SQLiteOpenHelper class must be overridden in the
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

LoginDB class. The method will be called by the system when creating the database:
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
/*
SQL instruction for creating the table accounts, which has two
columns, user and password.
Column user is primary key for the table, which means that its values
must be unique.
*/
sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME +
" ("+ FIELD_USER + " TEXT PRIMARY KEY, " +
FIELD_PASSWORD + " TEXT);");
}
Data storage
5. SQL Database
❖The OnUpgrade() method of the SQLiteOpenHelper class must be overridden in the
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

LoginDB class. The method will be called by the system when the structure of the

database changed. In this example, the method is left empty.


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {

}
Data storage
5. SQL Database
❖ For inserting data into the “accounts” table, a dedicated method can be added to the
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

LoginDB class. Example:


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

public void addRecord(String user, String password)


{
//obtain an instance to the database
SQLiteDatabase db = getWritableDatabase();
//set the user and the password in a ContentValues object
ContentValues values = new ContentValues();
values.put(FIELD_USER, user);
values.put(FIELD_PASSWORD, password);
//call the INSERT statement, which inserts the pairs user and
password in the table accounts
db.insert(TABLE_NAME, null,values);
}
Data storage
5. SQL Database
❖For querying the elements from the “accounts” table, a dedicated method can be added
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

to the LoginDB class.

Example of a method that queries for the rows that have the column “user” equal to the
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

user given as parameter:


public String findPassword(String user) {
//obtain an instance to the database
SQLiteDatabase db = getReadableDatabase();
//create the SELECT statement and execute it with rawQuery method
Cursor cursor = db.rawQuery("SELECT " + FIELD_PASSWORD + " FROM " + TABLE_NAME
+ " WHERE " + FIELD_USER + " = ?", new String[]{user});
//Check if a single row was found matching the select statement
if (cursor.getCount() == 1) {
//go to that row
cursor.moveToFirst();
//read the value from the column with index 0 of that row
return cursor.getString(0);
} else {
//return null otherwise
return null; }
}
Data storage
5. SQL Database
❖ For deleting rows from the “accounts” table, a dedicated method can be added to the
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

LoginDB class.

This is an example of a method that deletes the rows that have the column “user” equal
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

to the user given as parameter:


public void deleteRecord(String user)
{
//obtain an instance to the database
SQLiteDatabase db = getWritableDatabase();
//Call the DELETE statement on the rows that matches the where clause
user column = user
db.delete(TABLE_NAME, FIELD_USER+" = ?", new String[]{user});
}
Data storage
5. SQL Database
❖For updating the values of a row in the “accounts” table, a dedicated method can be
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

added to the LoginDB class. Example of a method that updates the password on the row

that has the column “user” equal to the user given as parameter
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

public void updateRecord(String user, String password)


{
//obtain an instance to the database
SQLiteDatabase db = getWritableDatabase();
//set the user and the password in a ContentValues object
ContentValues values = new ContentValues();
values.put(FIELD_USER, user);
values.put(FIELD_PASSWORD, password);
/*
Call the UPDATE statement, which updates the columns user and
password with the values
from the ContentValues object on the row that matches the where
clause user column = user
*/
db.update(TABLE_NAME,values,FIELD_USER + " = ?", new String[]{user});
}
Data storage
Conclusions

❖There are advantages and disadvantages to using each of the different


FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

storage methods available. Shared Preferences is the easiest to use,

especially if you want to store discrete primitive data types. However,


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

internal and external storage is best for storing files such as music, videos,

and documents, while SQLite wins if you need to perform fast searches and

queries on your data.

❖Ultimately, the storage method you choose should depend on your data

types, the length of time you need the data, and how private you want the

data to be.

You might also like