Lecture 08, File Handling, Shared Preferences
Lecture 08, File Handling, Shared Preferences
Lecture 08, File Handling, Shared Preferences
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.
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);