You are on page 1of 40

Mobile Computing

Lecture #08
File Handling, Shared Preferences,
SQLite Database
Today’s Lecture
Data Storage
1. File Storage
2. SharedPreferences
3. SQLite Database
Persistent Storage
Data that is available among different sessions of an application is called
persistent data
For persistent storage data is stored on secondary storage disks, SD card etc.
Android categorizes its storage (to store file data) into internal memory (that
phone is equipped with when it is shipped) and external memory (SD cards)
Generally, internal memory files are private to application that creates them
External memory files are sharable among multiple applications and user.
Example
Internal memory could be private or shareable. An example of WhatsApp,
messages, themes, which are not accessible to user or any other application are
stored in internal private memory, whereas pictures, videos are stored in
internal sharable memory, which user or any other application can access.
One definition of external storage is shareable memory, which can have
readable or non-readable files.
Internal Storage:
Limited Memory but always available
Files saved are accessible by your own app
Files are deleted when app is uninstalled.
Use it, if you are sure that the files are only for your own application usage.
External Storage:
All the files are technically accessible by your app, other apps and even the user.
When the app is uninstalled, public files remain on disk, but private files and cache files are
deleted.
Use it, if you are not afraid for your files to have public access.
Use it, if you have large file, which cannot save in internal memory
Android File System
An Android phone user is generally concerned with only its features i.e.
receiving / making calls, sending / receiving SMS and email, taking pictures
etc. but developers are not that lucky (they need to know more)
Android uses multiple partitions to organize data into files and folders
Each partition stores a particular type of files into them and has its own
functionality
Six partitions are significantly important:
1. /boot
2. /system
3. /recovery
4. /data
5. /cache
6. /misc
Android File System … Partitions
One can view the phone partitions by exploring the internal files of phone or
even Android emulator (AVD)
1. Launch the AVD
2. Go to android-sdk/platform-tools directory
3. Run adb shell command on command prompt
4. Now run df command
5. Partitions are shown
Android File System … Partitions … boot Partition
This partition is responsible for booting the device
It contains the underlying Linux kernel and the ramdisk
Android device will not be able to boot if boot partition is not available or is
corrupted
If due to some reason boot partition is deleted, device will be able to boot
only if we install a new boot partition
New boot partition can be installed using a ROM that includes a /boot
partition
Android File System … Partitions … system Partition
System partition contains system information (entire Android OS)
Other than Android OS, it also contains all the preinstalled applications when
phone is shipped
Removing this partition or removing its contents will remove OS from device
making it un usable
Phone without system partition can still be booted and can be set for
recovery
Android File System … Partitions … recovery Partition
Specially designed for recovery of OS
Recovery partition can be considered as alternative boot partition
It allows a device to perform advanced recovery and maintenance tasks
 Plz Fill up the Form to Create an Account
Android File System … Partitions … data Partition
Contains user data (applications data)
Data includes phone contacts, SMS data, settings and all applications installed
by user
If you factory reset your device all data on this partition will be erased
removing all applications installed by user and applications data
Your partition will be like it was shipped by vendor or like when you installed
your custom ROM
Android File System … Partitions … cache Partition
In this partition, Android stores user’s frequently used data and application
components
Erasing this partition’s content will not affect your phone’s functioning
 Erasing cache partition will simply remove its contents
 Erased data will simply be built again once your start using your phone again
Android File System … Partitions … misc Partition
Contains miscellaneous system settings as on-off values
These settings include Carrier ID, USB configuration and certain hardware
settings etc.
This partition plays an important role in functioning of Android device
Removing this partition can make certain features of device unavailable or
not functioning properly
Reading/Writing File Data
Create an Activity containing views as:
1. EditText to input data from user
2. Button (Save Data) to save data into a file on button’s click event
3. Button (Append Data) to append data into file on button’s click event
4. Button (Load Data) load data from file
5. TextView (Show Loaded Data)
Create layout for Activity
Load views into Java code
Write event handler code
Activity Code
public class MainActivity extends AppCompatActivity {
EditText inputForFile;
TextView showData;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputForFile = (EditText) findViewById(R.id.file_write_input);
showData = (TextView) findViewById(R.id.file_data);
}
Activity Code … Save into file
public void saveData(View view){
String data = inputForFile.getText().toString();
try {
FileOutputStream stream = openFileOutput("data_file.dat", MODE_PRIVATE);
OutputStreamWriter writer = new OutputStreamWriter(stream);
writer.write(data);
writer.flush();
writer.close();
Toast.makeText(MainActivity.this, "Data Saved Successfully",
Toast.LENGTH_LONG).show();
inputForFile.setText("");
}catch (FileNotFoundException exc){
Toast.makeText(MainActivity.this, “File not found error", Toast.LENGTH_LONG).show();
}catch (IOException exc){
Toast.makeText(MainActivity.this, “IO Exception occured", Toast.LENGTH_LONG).show();
}
}
Activity Code … Append to file
public void appendData(View view){
String data = inputForFile.getText().toString();
try {
FileOutputStream stream = openFileOutput("data_file.dat", MODE_APPEND);
OutputStreamWriter writer = new OutputStreamWriter(stream);
writer.write(data);
writer.flush();
writer.close();
Toast.makeText(MainActivity.this, "Data Saved Successfully",
Toast.LENGTH_LONG).show();
inputForFile.setText("");
}catch (FileNotFoundException exc){
Toast.makeText(MainActivity.this, “File not found error", Toast.LENGTH_LONG).show();
}catch (IOException exc){
Toast.makeText(MainActivity.this, “IO Exception occured", Toast.LENGTH_LONG).show();
}
}
Activity Code … Load from file
public void loadData(View view){
try{
FileInputStream stream = openFileInput("data_file.dat");
InputStreamReader reader = new InputStreamReader(stream);
char[] buffer = new char[50];
String data="";
int charRead =0;
while((charRead=reader.read(buffer))>0){
String string = String.copyValueOf(buffer, 0, charRead);
data += string;
buffer = new char[50];
}
showData.setText(data);
Toast.makeText(MainActivity.this, "Data Loaded Successfully",
Toast.LENGTH_LONG).show();
reader.close();
}catch (IOException exc){
Toast.makeText(MainActivity.this, "IO Exception", Toast.LENGTH_LONG).show();
}
File IO … Sample Problem ZERO
Write an Android application that allows you to write product reviews. You can write
reviews in a file along with product name.

Your application should be able to load reviews from file too.


File IO … Sample Problem 01
Write down an Android application that allows user to make business entries in text
files. Every entry in text file is as:
Person-Name, Paid/Received, Amount, Date
Write down code to implement following functions:
void addEntry(String name, boolean paid, int amount, String “MM-DD-YY”)
int getTotalAmount(String name)
int getTotalReceivedAmount(String startDate, String endDate)
int getTotalPaidAmount(String startDate, String endDate)

Implement appropriate UI and event handlers.


File IO … Sample Problem 02
Extend the sample problem 1 with following functionality:
 App uses separate file for every customer name
 File name of every customer must be same as customer name
 App also allows us to create a graph of amount received customer wise
 App also allows us to create a graph of amount paid customer wise
File IO … Sample Problem 03
A user makes a note for each of his important incidents using an Android application.
He adds date/time, person, small detail and place where that incident occurred. These
incidents are recorded into a text file.
Application offers following functionalities:
1. Showing the list of incidents
1. Between start date and end date
2. Showing incidents relevant to a place
1. Between start date and end date
2. After a particular date
3. Before a particular date
4. On a particular date
3. Showing incidents relevant to a person
1. All incidents
2. Incidents on a particular place
Reading/Writing to SD Card
An Android application can read / write data into external storage (SD card)
Data written will be in the form of files
There is no special security in Android for SD card reading/writing in place
Before reading/writing to sd card, it will be wise to check its presence
Reading/Writing to SD Card … Permission
Before an application can read/write, it must ask for permission in
application’s manifest file as
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Precaution for Reading/Writing to SD Card
Check the presence of SD Card
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
Precaution for Reading/Writing to SD Card
Check whether the SD Card is Read Only
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
Precaution for Reading/Writing to SD Card
if(!(isExternalStorageAvailable()) || isExternalStorageReadOnly()) {
writeToFileButton.setEnabled(false);
appendToFileButton.setEnabled(false);
}
Shared Preferences
What are Shared Preferences?
How to use Shared Preferences?
Shared Preferences Operations
Shared Preferences Examples
1. Retrieving Shared Preferences
2. Creating/Updating Shared Preferences
3. Shared Preferences Scenarios
Shared Preference
Android provides many ways of storing data of an application. One of this ways is
called Shared Preferences. Shared Preferences allow you to save and retrieve data in
the form of key value pair.
Key is always String, value can have either primitive type (string, long, int ,float,
and Boolean) or String type.

Shared Preference provide persistence storage, however Shared Preferences is


application specific, i.e. the data is lost on performing one of the following options:
On uninstalling the application
On clearing the application data (through Settings)
Shared Perference
As the name suggests, the primary purpose is to store user-specified
configuration details, such as user specific setting, keeping the user
logged into the application. For example when the user’s settings need
to be saved or to store data that can be used in different activities within
the app.
• Persist Data across user sessions, even if app is killed and restarted, or
device is rebooted
• Data that should be remembered across sessions, such as user’s
preferred settings or their game score.
• Common use is to store user preferences
Shared Preferences
Shared Preferences is a way to store data persistently in the form of key-value
pairs
Key is always String, value can have either primitive type or String type
Shared Preferences are generally used to store application settings
Android supports two types of Preferences i. Application Level ii. Activity
Level
Path to Shared Preferences File
 SharedPreference containers are saved as XML files in the application’s internal memory
space
 The path to a preference files is /data/data/packageName/shared_prefs/filename
 One could always explore the internal memory of phone and locate the preferences file
 If you can pull the preferences as in previous slide, following contents should be seen:

<?xml version=“1.0” encoding=“UTF-8” standalone=“true”?>


<map>
<string name=“user_name”>guest</string>
<int name=“max_tries” value=“3”/>
</map>
Shared Preference
In order to use shared preferences, you have to call a method
getSharedPreferences()/getPreferences() that return a SharedPreference
instance pointing to the file that contain the values of prererence.
SharedPreferences sferences = getSharedPreferences( String name, int MODE);
getPreference(int MODE): Takes no argument, This will open or create a
preference file with out giving a name specifically. By default preference file
name will be the current Activity name.
getSharedPerference(String file-name, int Mode): It will open or create a
preference file with the given name. Use this function, if you want multiple
preference files for you activity, 
SharedPreference Mode
• MODE_PUBLIC: will make the file public which could be accessible by
other application in the device.
• MODE_PRIVATE: keeps the files private and secure user’s data.
• MODE_APPEND: will append the new preferences with the already
existing preferences
• MODE_WORLD_READABLE: allow the other application to read the
Preference file.
• MODE_WORLD_WRITEABLE: allow the other application to write the
Preference file.
Creating/Updating Shared Preferences
Following an example to create Shared Preferences in an application:

SharedPreferences prefs = getSharedPreferences(“app_prefs”, Activity.MODE_PRIVATE);


SharedPreferences.Editor editor = prefs.edit();

 To save data in SharedPreferences developer need to called edit() function of SharedPreferences class which


returns Editor class object. Editor class provide different function to save primitive time data.
 Make sure that key name should be unique for any values you save otherwise it will be overrided.

editor.putString(“name”, “guest”);
editor.putInt(“max_tries”, 3);

 To exactly save the values you put in different primitive functions you must call commit() function of Editor.
editor.commit();
Creating Shared Preferences
1. SharedPreferences prefs = getSharedPreferences(“app_prefs”, Activity.MODE_PRIVATE);
2. SharedPreferences.Editor editor = prefs.edit();
3. editor.putString(“user_name”, “guest”);
4. editor.putInt(“max_tries”, 3);
5. editor.commit();

Line 1 retrieves the preferences if they already exist. Otherwise, it creates them.
Line 2 gets an editor instance to update preferences.
Line 3 creates a pair of preference with a String value.
Line 4 creates a pair of preference with an int value.
Line 5 tells the editor that required changes have been completed i.e. preferences must stop
accepting changes into them.
Retrieving Shared Preferences
SharedPreferences prefs = getSharedPreferences(“app_prefs”, Activity.MODE_PRIVATE);
String userName = prefs.getString(“user_name”, “guest”);
int maxTries = prefs.getInt(“max_tries”, 1);

1. Create Shared Preferences instance


2. Using the created instance in step 1, call appropriate function to retrieve the value of
preference
3. Use the value in your app
Remove or Clear Preference
• remove(“key_name”) is used to delete that particular value.
editor.remove("name"); // will delete key name
editor.commit(); // commit changes

• clear() is used to remove all data


editor.clear();
editor.commit(); // commit changes
Shared Preferences … Sample Problem 01
Create an application that when launched very first time, signup Activity appears in front
of user and asks for user_name and favourite_color. Received data is stored into shared
preferences.
When application is launched subsequently, user is straight away taken to dash board
Activity showing the possible operations user can perform i.e. make a call, send SMS, send
an email etc.
https://www.javatpoint.com/kotlin-android-sharedpreferences
Shared Preferences … Sample Problem 02
Create an application that when launched very first time, asks user to select his/her class
and class section. Received data is stored into shared preferences.
When application is launched subsequently, user is straight away taken to time table
Activity showing the time table for selected class / section.
Shared Preferences … Sample Problem 03
Create an application that when launched very first time, asks user to select his preferred
package for cable-tv. Received data is stored into shared preferences.
When application is launched subsequently, user is straight away taken to channels list
Activity showing him the channels included in his package. Moreover, activity background
is shown automatically as per selected package.

You might also like