SlideShare a Scribd company logo
1 of 9
Chapter 21
Data Storage in Android
By
Dr. Ramkumar Lakshminarayanan
Introduction
Data Storage in Andorid used to store application data in databases, files, or
preferences, in internal or removeable storage. Used to add a data backup service to let users
store and recover application and system data.
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.
Your 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.
Android provides a way for you to expose even your private data to other applications
— with a content provider. A content provider is an optional component that exposes
read/write access to your application data, subject to whatever restrictions you want to
impose
Shared Preferences
The SharedPreferences class provides a general framework that allows you to save
and retrieve persistent key-value pairs of primitive data types. You can
use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings.
This data will persist across user sessions (even if your application is killed).
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what
ringtone a user has chosen. If you're interested in creating user preferences for your
application, whiich provides an Activity framework for you to create user preferences, which
will be automatically persisted (using shared preferences).
To get a SharedPreferences object for your application, use one of two methods:
 getSharedPreferences() - Use this if you need multiple preferences files identified by
name, which you specify with the first parameter.
 getPreferences() - Use this if you need only one preferences file for your Activity.
Because this will be the only preferences file for your Activity, you don't supply a
name.
To write values:
 Call edit() to get a SharedPreferences.Editor.
 Add values with methods such as putBoolean() and putString().
 Commit the new values with commit()
 To read values, use SharedPreferences methods such as getBoolean() and getString().
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:
 Call openFileOutput() with the name of the file and the operating mode. This returns a
FileOutputStream.
 Write to the file with write().
 Close the stream with close().
Example Code
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
MODE_PRIVATE will create the file (or replace a file of the same name) and make it
private to your application. Other modes available
are: MODE_APPEND, MODE_WORLD_READABLE,
and MODE_WORLD_WRITEABLE
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().
getFilesDir()
Gets the absolute path to the filesystem directory where your internal files are saved.
getDir()
Creates (or opens an existing) directory within your internal storage space.
deleteFile()
Deletes a file saved on the internal storage.
fileList()
Returns an array of files currently saved by your application.
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.
It's possible that a device using a partition of the internal storage for the external
storage may also offer an SD card slot. In this case, the SD card is not part of the external
storage and your app cannot access it (the extra storage is intended only for user-provided
media that the system scans).
Before you do any work with the external storage, you should always call
getExternalStorageState() to check whether the media is available. The media might be
mounted to a computer, missing, read-only, or in some other state. For example, here's how
you can check the availability:
Example Code
This example checks whether the external storage is available to read and write. The
getExternalStorageState() method returns other states that you might want to check, such as
whether the media is being shared (connected to a computer), is missing entirely, has been
removed badly, etc. You can use these to notify the user with more information when your
application needs to access the media.
Database
Android provides full support for SQLite databases. Any databases you create will be
accessible by name to any class in the application, but not outside the application.
The recommended method to create a new SQLite database is to create a subclass of
SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite
command to create tables in the database.
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
Example Code
You can then get an instance of your SQLiteOpenHelper implementation using the
constructor you've defined. To write to and read from the database, call
getWritableDatabase() and getReadableDatabase(), respectively. These both return a
SQLiteDatabase object that represents the database and provides methods for SQLite
operations.
Android does not impose any limitations beyond the standard SQLite concepts. We
do recommend including an autoincrement value key field that can be used as a unique ID to
quickly find a record. This is not required for private data, but if you implement a content
provider, you must include a unique ID using the BaseColumns._ID constant.
You can execute SQLite queries using the SQLiteDatabase query() methods, which
accept various query parameters, such as the table to query, the projection, selection,
public class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}
columns, grouping, and others. For complex queries, such as those that require column
aliases, you should use SQLiteQueryBuilder, which provides several convienent methods for
building queries.
Every SQLite query will return a Cursor that points to all the rows found by the
query. The Cursor is always the mechanism with which you can navigate results from a
database query and read rows and columns.
Example - Shared Preference
1. Create a new project and call it Preferences,
2. In the res-layoutactivity_main use the following code to create buttons
3. Import following packages in your code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="MY BUTTON"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/show_saved_data"
android:text="SHOW SAVED DATA"/>
</LinearLayout>
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
package com.mjs.preference;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.view.Menu;
public class MainActivity extends Activity {
private Button mMyButton;
private Button mShow;
private String mDataString;
private String mGetSavedData;
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMyButton = (Button)findViewById(R.id.button);
mShow = (Button)findViewById(R.id.show_saved_data);
//restore the saved data
SharedPreferences preferences = getSharedPreferences("pref", 0);
mGetSavedData = preferences.getString("savedData", "default value");
mMyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//in mDataString we put the name of mMyButton when we click it
mDataString = mMyButton.getText().toString();
}
});
mShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, mGetSavedData,1).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
protected void onPause() {
super.onPause();
//save the data
SharedPreferences preferences = getSharedPreferences("pref", 0);
SharedPreferences.Editor editor = preferences.edit();
//"savedData" is the key that we will use in onCreate to get the saved data
//mDataString is the string we want to save
editor.putString("savedData", mDataString);
// commit the edits
editor.commit();
}
}
The "pref" key and "savedData" key must be the same in onPause and in onCreate.
The "default value" from mGetSavedData = preferences.getString("savedData", "default
value"); represents the value to return if the value does not exist.
Now run your application and click first the "Show Saved Data" button. You will see
the default value like in the picture below, because you didn't exit the application so the
onPause to be called. This step is just to see the difference between saved data and unsaved
data.
Figure 21.1 Showing default value
Click the button "MY BUTTON". Now in the string mDataString you must have the
name of the button. Now press the back button. At this step the onPause was called and the
mDataString is stored.
Reopen the application and press the "SHOW SAVED DATA" and it will display the
name of "MY BUTTON" like in the picture below.
Figure 21.2 Showing Stored Value
In this example we have seen about storing a value using the shared preference
Summary
Android provides various options for storing the data. Among them are Shared
Preferences, Internal Storage, External Storage, SQLite Databases and Network Connection.
In this unit we have discussed about the usage of them and example of using Shared
Preference. In the next unit we will discuss about SQLite.

More Related Content

What's hot

SQLite Database Tutorial In Android
SQLite Database Tutorial In AndroidSQLite Database Tutorial In Android
SQLite Database Tutorial In AndroidAndroid 5
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database TutorialPerfect APK
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android ApplicationMark Lester Navarro
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1Umar Ali
 
Oracle dba interview
Oracle dba interviewOracle dba interview
Oracle dba interviewNaveen P
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorialinfo_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
E2D3 ver. 0.2 Development Instructions
E2D3 ver. 0.2 Development InstructionsE2D3 ver. 0.2 Development Instructions
E2D3 ver. 0.2 Development InstructionsE2D3.org
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WPNguyen Tuan
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalDr. Ranbijay Kumar
 
Dotnet differences compiled -1
Dotnet differences compiled -1Dotnet differences compiled -1
Dotnet differences compiled -1Umar Ali
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05Niit Care
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)Oum Saokosal
 
Apply hibernate to model and persist associations mappings in document versio...
Apply hibernate to model and persist associations mappings in document versio...Apply hibernate to model and persist associations mappings in document versio...
Apply hibernate to model and persist associations mappings in document versio...csandit
 

What's hot (20)

Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
SQLite Database Tutorial In Android
SQLite Database Tutorial In AndroidSQLite Database Tutorial In Android
SQLite Database Tutorial In Android
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Storage 8
Storage   8Storage   8
Storage 8
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1
 
Oracle dba interview
Oracle dba interviewOracle dba interview
Oracle dba interview
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
E2D3 ver. 0.2 Development Instructions
E2D3 ver. 0.2 Development InstructionsE2D3 ver. 0.2 Development Instructions
E2D3 ver. 0.2 Development Instructions
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and Retrieval
 
Dotnet differences compiled -1
Dotnet differences compiled -1Dotnet differences compiled -1
Dotnet differences compiled -1
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)
 
Apply hibernate to model and persist associations mappings in document versio...
Apply hibernate to model and persist associations mappings in document versio...Apply hibernate to model and persist associations mappings in document versio...
Apply hibernate to model and persist associations mappings in document versio...
 

Similar to Data Storage Options in Android

12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptxFaezNasir
 
Mobile Application Development-Lecture 13 & 14.pdf
Mobile Application Development-Lecture 13 & 14.pdfMobile Application Development-Lecture 13 & 14.pdf
Mobile Application Development-Lecture 13 & 14.pdfAbdullahMunir32
 
Android session 4-behestee
Android session 4-behesteeAndroid session 4-behestee
Android session 4-behesteeHussain Behestee
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 StorageDiego Grancini
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storageMengChun Lam
 
Mobile Application Development -Lecture 11 & 12.pdf
Mobile Application Development -Lecture 11 & 12.pdfMobile Application Development -Lecture 11 & 12.pdf
Mobile Application Development -Lecture 11 & 12.pdfAbdullahMunir32
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Khaled Anaqwa
 
"Android" mobilių programėlių kūrimo įvadas #3
"Android" mobilių programėlių kūrimo įvadas #3"Android" mobilių programėlių kūrimo įvadas #3
"Android" mobilių programėlių kūrimo įvadas #3Tadas Jurelevičius
 
Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015Cindy Potvin
 
Android booting sequece and setup and debugging
Android booting sequece and setup and debuggingAndroid booting sequece and setup and debugging
Android booting sequece and setup and debuggingUtkarsh Mankad
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptxvishal choudhary
 
iOS Course day 2
iOS Course day 2iOS Course day 2
iOS Course day 2Rich Allen
 

Similar to Data Storage Options in Android (20)

12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx
 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
Mobile Application Development-Lecture 13 & 14.pdf
Mobile Application Development-Lecture 13 & 14.pdfMobile Application Development-Lecture 13 & 14.pdf
Mobile Application Development-Lecture 13 & 14.pdf
 
Android session 4-behestee
Android session 4-behesteeAndroid session 4-behestee
Android session 4-behestee
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 Storage
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
 
Mobile Application Development -Lecture 11 & 12.pdf
Mobile Application Development -Lecture 11 & 12.pdfMobile Application Development -Lecture 11 & 12.pdf
Mobile Application Development -Lecture 11 & 12.pdf
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)
 
"Android" mobilių programėlių kūrimo įvadas #3
"Android" mobilių programėlių kūrimo įvadas #3"Android" mobilių programėlių kūrimo įvadas #3
"Android" mobilių programėlių kūrimo įvadas #3
 
Data management
Data managementData management
Data management
 
Data management
Data managementData management
Data management
 
Lab4 - android
Lab4 - androidLab4 - android
Lab4 - android
 
MA DHARSH.pptx
MA DHARSH.pptxMA DHARSH.pptx
MA DHARSH.pptx
 
Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015
 
Android booting sequece and setup and debugging
Android booting sequece and setup and debuggingAndroid booting sequece and setup and debugging
Android booting sequece and setup and debugging
 
Level 4
Level 4Level 4
Level 4
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
iOS Course day 2
iOS Course day 2iOS Course day 2
iOS Course day 2
 
9 content-providers
9 content-providers9 content-providers
9 content-providers
 
GAAD Database presentation
GAAD Database presentationGAAD Database presentation
GAAD Database presentation
 

More from Dr. Ramkumar Lakshminarayanan

More from Dr. Ramkumar Lakshminarayanan (20)

IT security awareness
IT security awarenessIT security awareness
IT security awareness
 
Basics of IT security
Basics of IT securityBasics of IT security
Basics of IT security
 
IT Security Awareness Posters
IT Security Awareness PostersIT Security Awareness Posters
IT Security Awareness Posters
 
Normalisation revision
Normalisation revisionNormalisation revision
Normalisation revision
 
Windows mobile programming
Windows mobile programmingWindows mobile programming
Windows mobile programming
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
 
Web technology today
Web technology todayWeb technology today
Web technology today
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Phonegap for Android
Phonegap for AndroidPhonegap for Android
Phonegap for Android
 
Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)Create and Sell Android App (in tamil)
Create and Sell Android App (in tamil)
 
Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)Android app - Creating Live Wallpaper (tamil)
Android app - Creating Live Wallpaper (tamil)
 
Android Tips (Tamil)
Android Tips (Tamil)Android Tips (Tamil)
Android Tips (Tamil)
 
Android Animation (in tamil)
Android Animation (in tamil)Android Animation (in tamil)
Android Animation (in tamil)
 
Creating List in Android App (in tamil)
Creating List in Android App (in tamil)Creating List in Android App (in tamil)
Creating List in Android App (in tamil)
 
Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)Single Touch event view in Android (in tamil)
Single Touch event view in Android (in tamil)
 
Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)Android Application using seekbar (in tamil)
Android Application using seekbar (in tamil)
 
Rating Bar in Android Example
Rating Bar in Android ExampleRating Bar in Android Example
Rating Bar in Android Example
 
Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)Creating Image Gallery - Android app (in tamil)
Creating Image Gallery - Android app (in tamil)
 
Create Android App using web view (in tamil)
Create Android App using web view (in tamil)Create Android App using web view (in tamil)
Create Android App using web view (in tamil)
 
Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)Hardware Interface in Android (in tamil)
Hardware Interface in Android (in tamil)
 

Data Storage Options in Android

  • 1. Chapter 21 Data Storage in Android By Dr. Ramkumar Lakshminarayanan Introduction Data Storage in Andorid used to store application data in databases, files, or preferences, in internal or removeable storage. Used to add a data backup service to let users store and recover application and system data. 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. Your 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. Android provides a way for you to expose even your private data to other applications — with a content provider. A content provider is an optional component that exposes read/write access to your application data, subject to whatever restrictions you want to impose Shared Preferences The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can
  • 2. use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed). User Preferences Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, whiich provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences). To get a SharedPreferences object for your application, use one of two methods:  getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.  getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name. To write values:  Call edit() to get a SharedPreferences.Editor.  Add values with methods such as putBoolean() and putString().  Commit the new values with commit()  To read values, use SharedPreferences methods such as getBoolean() and getString(). 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:  Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream.  Write to the file with write().  Close the stream with close(). Example Code String FILENAME = "hello_file"; String string = "hello world!"; FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close();
  • 3. MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE 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(). getFilesDir() Gets the absolute path to the filesystem directory where your internal files are saved. getDir() Creates (or opens an existing) directory within your internal storage space. deleteFile() Deletes a file saved on the internal storage. fileList() Returns an array of files currently saved by your application. 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. It's possible that a device using a partition of the internal storage for the external storage may also offer an SD card slot. In this case, the SD card is not part of the external storage and your app cannot access it (the extra storage is intended only for user-provided media that the system scans). Before you do any work with the external storage, you should always call getExternalStorageState() to check whether the media is available. The media might be mounted to a computer, missing, read-only, or in some other state. For example, here's how you can check the availability:
  • 4. Example Code This example checks whether the external storage is available to read and write. The getExternalStorageState() method returns other states that you might want to check, such as whether the media is being shared (connected to a computer), is missing entirely, has been removed badly, etc. You can use these to notify the user with more information when your application needs to access the media. Database Android provides full support for SQLite databases. Any databases you create will be accessible by name to any class in the application, but not outside the application. The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database. boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; }
  • 5. Example Code You can then get an instance of your SQLiteOpenHelper implementation using the constructor you've defined. To write to and read from the database, call getWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations. Android does not impose any limitations beyond the standard SQLite concepts. We do recommend including an autoincrement value key field that can be used as a unique ID to quickly find a record. This is not required for private data, but if you implement a content provider, you must include a unique ID using the BaseColumns._ID constant. You can execute SQLite queries using the SQLiteDatabase query() methods, which accept various query parameters, such as the table to query, the projection, selection, public class DictionaryOpenHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 2; private static final String DICTIONARY_TABLE_NAME = "dictionary"; private static final String DICTIONARY_TABLE_CREATE = "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" + KEY_WORD + " TEXT, " + KEY_DEFINITION + " TEXT);"; DictionaryOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DICTIONARY_TABLE_CREATE); } }
  • 6. columns, grouping, and others. For complex queries, such as those that require column aliases, you should use SQLiteQueryBuilder, which provides several convienent methods for building queries. Every SQLite query will return a Cursor that points to all the rows found by the query. The Cursor is always the mechanism with which you can navigate results from a database query and read rows and columns. Example - Shared Preference 1. Create a new project and call it Preferences, 2. In the res-layoutactivity_main use the following code to create buttons 3. Import following packages in your code <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello World, MyActivity"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button" android:text="MY BUTTON"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/show_saved_data" android:text="SHOW SAVED DATA"/> </LinearLayout> import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast;
  • 7. package com.mjs.preference; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import android.view.Menu; public class MainActivity extends Activity { private Button mMyButton; private Button mShow; private String mDataString; private String mGetSavedData; /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMyButton = (Button)findViewById(R.id.button); mShow = (Button)findViewById(R.id.show_saved_data); //restore the saved data SharedPreferences preferences = getSharedPreferences("pref", 0); mGetSavedData = preferences.getString("savedData", "default value"); mMyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //in mDataString we put the name of mMyButton when we click it mDataString = mMyButton.getText().toString(); } }); mShow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, mGetSavedData,1).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } protected void onPause() { super.onPause(); //save the data SharedPreferences preferences = getSharedPreferences("pref", 0); SharedPreferences.Editor editor = preferences.edit(); //"savedData" is the key that we will use in onCreate to get the saved data //mDataString is the string we want to save editor.putString("savedData", mDataString); // commit the edits editor.commit(); } }
  • 8. The "pref" key and "savedData" key must be the same in onPause and in onCreate. The "default value" from mGetSavedData = preferences.getString("savedData", "default value"); represents the value to return if the value does not exist. Now run your application and click first the "Show Saved Data" button. You will see the default value like in the picture below, because you didn't exit the application so the onPause to be called. This step is just to see the difference between saved data and unsaved data. Figure 21.1 Showing default value Click the button "MY BUTTON". Now in the string mDataString you must have the name of the button. Now press the back button. At this step the onPause was called and the mDataString is stored. Reopen the application and press the "SHOW SAVED DATA" and it will display the name of "MY BUTTON" like in the picture below.
  • 9. Figure 21.2 Showing Stored Value In this example we have seen about storing a value using the shared preference Summary Android provides various options for storing the data. Among them are Shared Preferences, Internal Storage, External Storage, SQLite Databases and Network Connection. In this unit we have discussed about the usage of them and example of using Shared Preference. In the next unit we will discuss about SQLite.