SlideShare a Scribd company logo
Data Storage
Topics
• Data storage options
• Shared preferences
• Internal storage
• External storage
• Database
• Network connection
Data Storage Options
Data Storage Options in Android
• 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)
> how much space your data requires.
Data Storage Options
• 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.
Content Provider
&
Data Storage
Content Provider & Data Storage
• Most content providers store their data using
Android's file storage methods or SQLite
databases, but you can store your data any way
you want.
Shared Preferences
When to Use 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).
PreferenceActivity Class
• If you're interested in creating user preferences
for your application, see PreferenceActivity,
which provides an Activity framework for you to
create user preferences, which will be
automatically persisted (using shared
preferences underneath).
How to Use Shared Preferences? (1)
• 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.
How to Use Shared Preferences? (2)
• 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()
Example: Using Shared Preferences
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
Internal Storage
Using 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
• When the user uninstalls your application,
these files are removed.
How to Use Internal Storage?
• 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
object
> Write to the file with write().
> Close the stream with close().
• To read a file from internal storage
> Call openFileInput() and pass it the name of the file
to read. This returns a FileInputStream.
> Read bytes from the file with read().
> Then close the stream with close().
Example: Using Internal Storage
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
Other Useful Methods
• 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
Using 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.
Checking Media Availability
• Before you do any work with the external
storage, you should always call
getExternalStorageState() to check the state of
the media
> Mounted
> Missing
> Read-only
> Some other state
Example: Checking Media State
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;
}
Accessing files on external storage (1)
• If you're using API Level 8 or greater, use
getExternalFilesDir() to open a File that
represents the external storage directory where
you should save your files
> This method takes a type parameter that specifies
the type of subdirectory you want, such as
DIRECTORY_MUSIC and DIRECTORY_RINGTONES
> This method will create the appropriate directory if
necessary.
> By specifying the type of directory, you ensure that
the Android's media scanner will properly categorize
your files in the system (for example, ringtones are
identified as ringtones and not music).
> If the user uninstalls your application, this directory
and all its contents will be deleted.
Accessing files on external storage (2)
• If you're using API Level 7 or lower, use
getExternalStorageDirectory(), to open a File
representing the root of the external storage.
You should then write your data in the following
directory:
> /Android/data/<package_name>/files/ (where
<package_name> is your Java-style package name,
such as "com.example.android.app")
Saving Files that Should be Shared (1)
• If you want to save files that are not specific to
your application and that should not be deleted
when your application is uninstalled, save them
to one of the public directories on the external
storage.
> These directories lay at the root of the external
storage, such as Music/, Pictures/, Ringtones/, and
others.
Saving Files that Should be Shared (2)
• In API Level 8 or greater
> Use getExternalStoragePublicDirectory(), passing it
the type of public directory you want, such as
DIRECTORY_MUSIC, DIRECTORY_PICTURES,
DIRECTORY_RINGTONES, or others.
> This method will create the appropriate directory if
necessary.
• In API Level 7 or lower
> Use getExternalStorageDirectory() to open a File that
represents the root of the external storage, then
save your shared files in one of the following
directories:
> Music/, Podcasts/, Ringtones/, Alarms/, Notifications/,
Pictures/, Movies/, Download/
Using Databases
Using Databases
• Android provides full support for SQLite
databases.
> SQLite is a software library that implements a self-
contained, serverless, zero-configuration,
transactional SQL database engine.
• Any databases you create will be accessible 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.
Using Databases - Two Options
• Option #1
> 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.
> Then use execSQL() for executing SQL
• Option #2
> Use openOrCreateDatabase() to create
SQLiteDatabase
> Then use execSQL() for executing SQL
Option #1: Create Database & Table
public class MyDbOpenHelper 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);
}
}
Option #2: Creating Database & Table
private static final String DATABASE_NAME = "myDB.db";
private static final String DATABASE_TABLE_NAME = "COUNTRY";
private static final String DATABASE_CREATE_TABLE =
"create table " + DATABASE_TABLE_NAME +
" (_id integer primary key autoincrement, " +
" country_name text not null, " +
" capital_city text not null)";
// Open a new private SQLiteDatabase associated with this Context's application
// package. Create the database file if it doesn't exist.
SQLiteDatabase myDB = openOrCreateDatabase(
DATABASE_NAME,
Context.MODE_PRIVATE, null);
// Create database table
myDB.execSQL(DATABASE_CREATE_TABLE);
Example: Inserting a row
SQLiteDatabase myDB = openOrCreateDatabase(DATABASE_NAME,
Context.MODE_PRIVATE, null);
// Create a new row and insert it into the database.
ContentValues newRow = new ContentValues();
newRow.put("country_name", "U.S.A.");
newRow.put("capital_city", "Washington D.C.");
myDB.insert(DATABASE_TABLE_NAME, null, newRow);
Example: Retrieving all rows
SQLiteDatabase myDB = openOrCreateDatabase(DATABASE_NAME,
Context.MODE_PRIVATE, null);
// Select columns to retrieve in the form of String array
String[] resultColumns = new String[] {"_id", "country_name", "capital_city"};
Cursor cursor = myDB.query(DATABASE_TABLE_NAME, resultColumns, null, null,
null, null, null, null);
String res = "Result is:";
Integer cindex = cursor.getColumnIndex("country_name");
if (cursor.moveToFirst()) {
do {
res += cursor.getString(cindex)+"-";
} while (cursor.moveToNext());
}
Thank you
Ad

More Related Content

What's hot (20)

Database in Android
Database in AndroidDatabase in Android
Database in Android
MaryadelMar85
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
Sergi Martínez
 
Android Intent.pptx
Android Intent.pptxAndroid Intent.pptx
Android Intent.pptx
vishal choudhary
 
android layouts
android layoutsandroid layouts
android layouts
Deepa Rani
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
Prawesh Shrestha
 
Shared preferences
Shared preferencesShared preferences
Shared preferences
Sourabh Sahu
 
AndroidManifest
AndroidManifestAndroidManifest
AndroidManifest
Ahsanul Karim
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
Nakka Srilakshmi
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
Haldia Institute of Technology
 
ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
baabtra.com - No. 1 supplier of quality freshers
 
Fragments In Android
Fragments In AndroidFragments In Android
Fragments In Android
DivyaKS12
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
priya Nithya
 
Android Services
Android ServicesAndroid Services
Android Services
Ahsanul Karim
 
Android resource
Android resourceAndroid resource
Android resource
Krazy Koder
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Content provider in_android
Content provider in_androidContent provider in_android
Content provider in_android
PRITI TELMORE
 
Visual Studio IDE
Visual Studio IDEVisual Studio IDE
Visual Studio IDE
Sayantan Sur
 
Architecture of .net framework
Architecture of .net frameworkArchitecture of .net framework
Architecture of .net framework
Then Murugeshwari
 
Broadcast Receiver
Broadcast ReceiverBroadcast Receiver
Broadcast Receiver
nationalmobileapps
 
Android Multimedia Support
Android Multimedia SupportAndroid Multimedia Support
Android Multimedia Support
Jussi Pohjolainen
 

Similar to Android datastorage (20)

Storage 8
Storage   8Storage   8
Storage 8
Michael Shrove
 
Android session 4-behestee
Android session 4-behesteeAndroid session 4-behestee
Android session 4-behestee
Hussain Behestee
 
Android-data storage in android-chapter21
Android-data storage in android-chapter21Android-data storage in android-chapter21
Android-data storage in android-chapter21
Dr. Ramkumar Lakshminarayanan
 
Memory management
Memory managementMemory management
Memory management
Vikash Patel
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
Jussi Pohjolainen
 
Lab4 - android
Lab4 - androidLab4 - android
Lab4 - android
Lilia Sfaxi
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 Storage
Diego Grancini
 
Mobile application Development-UNIT-V (1).pptx
Mobile application Development-UNIT-V (1).pptxMobile application Development-UNIT-V (1).pptx
Mobile application Development-UNIT-V (1).pptx
JayasimhaThummala1
 
12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx
FaezNasir
 
Assets, files, and data parsing
Assets, files, and data parsingAssets, files, and data parsing
Assets, files, and data parsing
Aly Arman
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)
Khaled Anaqwa
 
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
AbdullahMunir32
 
Level 4
Level 4Level 4
Level 4
skumartarget
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
MengChun Lam
 
Mobile Application Development (Shared Preferences) class-06
Mobile Application Development (Shared Preferences) class-06Mobile Application Development (Shared Preferences) class-06
Mobile Application Development (Shared Preferences) class-06
Dr. Mazin Mohamed alkathiri
 
Corporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbaiCorporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbai
Unmesh Baile
 
Corporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbaiCorporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbai
Unmesh Baile
 
MA DHARSH.pptx
MA DHARSH.pptxMA DHARSH.pptx
MA DHARSH.pptx
DharshiniB15
 
Android local databases
Android local databasesAndroid local databases
Android local databases
FatimaYousif11
 
Devday 2014 using_afs_in_your_cloud_app
Devday 2014 using_afs_in_your_cloud_appDevday 2014 using_afs_in_your_cloud_app
Devday 2014 using_afs_in_your_cloud_app
Mihail Mateev
 
Android session 4-behestee
Android session 4-behesteeAndroid session 4-behestee
Android session 4-behestee
Hussain Behestee
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 Storage
Diego Grancini
 
Mobile application Development-UNIT-V (1).pptx
Mobile application Development-UNIT-V (1).pptxMobile application Development-UNIT-V (1).pptx
Mobile application Development-UNIT-V (1).pptx
JayasimhaThummala1
 
12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx
FaezNasir
 
Assets, files, and data parsing
Assets, files, and data parsingAssets, files, and data parsing
Assets, files, and data parsing
Aly Arman
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)
Khaled Anaqwa
 
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
AbdullahMunir32
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
MengChun Lam
 
Mobile Application Development (Shared Preferences) class-06
Mobile Application Development (Shared Preferences) class-06Mobile Application Development (Shared Preferences) class-06
Mobile Application Development (Shared Preferences) class-06
Dr. Mazin Mohamed alkathiri
 
Corporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbaiCorporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbai
Unmesh Baile
 
Corporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbaiCorporate-informatica-training-in-mumbai
Corporate-informatica-training-in-mumbai
Unmesh Baile
 
Android local databases
Android local databasesAndroid local databases
Android local databases
FatimaYousif11
 
Devday 2014 using_afs_in_your_cloud_app
Devday 2014 using_afs_in_your_cloud_appDevday 2014 using_afs_in_your_cloud_app
Devday 2014 using_afs_in_your_cloud_app
Mihail Mateev
 
Ad

More from Krazy Koder (20)

2310 b xd
2310 b xd2310 b xd
2310 b xd
Krazy Koder
 
2310 b xd
2310 b xd2310 b xd
2310 b xd
Krazy Koder
 
2310 b xd
2310 b xd2310 b xd
2310 b xd
Krazy Koder
 
2310 b xc
2310 b xc2310 b xc
2310 b xc
Krazy Koder
 
2310 b xb
2310 b xb2310 b xb
2310 b xb
Krazy Koder
 
2310 b 17
2310 b 172310 b 17
2310 b 17
Krazy Koder
 
2310 b 16
2310 b 162310 b 16
2310 b 16
Krazy Koder
 
2310 b 16
2310 b 162310 b 16
2310 b 16
Krazy Koder
 
2310 b 15
2310 b 152310 b 15
2310 b 15
Krazy Koder
 
2310 b 15
2310 b 152310 b 15
2310 b 15
Krazy Koder
 
2310 b 14
2310 b 142310 b 14
2310 b 14
Krazy Koder
 
2310 b 13
2310 b 132310 b 13
2310 b 13
Krazy Koder
 
2310 b 12
2310 b 122310 b 12
2310 b 12
Krazy Koder
 
2310 b 11
2310 b 112310 b 11
2310 b 11
Krazy Koder
 
2310 b 10
2310 b 102310 b 10
2310 b 10
Krazy Koder
 
2310 b 09
2310 b 092310 b 09
2310 b 09
Krazy Koder
 
2310 b 08
2310 b 082310 b 08
2310 b 08
Krazy Koder
 
2310 b 08
2310 b 082310 b 08
2310 b 08
Krazy Koder
 
2310 b 08
2310 b 082310 b 08
2310 b 08
Krazy Koder
 
2310 b 07
2310 b 072310 b 07
2310 b 07
Krazy Koder
 
Ad

Recently uploaded (20)

SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 

Android datastorage

  • 2. Topics • Data storage options • Shared preferences • Internal storage • External storage • Database • Network connection
  • 4. Data Storage Options in Android • 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) > how much space your data requires.
  • 5. Data Storage Options • 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.
  • 7. Content Provider & Data Storage • Most content providers store their data using Android's file storage methods or SQLite databases, but you can store your data any way you want.
  • 9. When to Use 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).
  • 10. PreferenceActivity Class • If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences underneath).
  • 11. How to Use Shared Preferences? (1) • 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.
  • 12. How to Use Shared Preferences? (2) • 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()
  • 13. Example: Using Shared Preferences public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onCreate(Bundle state){ super.onCreate(state); . . . // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); } @Override protected void onStop(){ super.onStop(); // We need an Editor object to make preference changes. // All objects are from android.context.Context SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); // Commit the edits! editor.commit(); } }
  • 15. Using 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 • When the user uninstalls your application, these files are removed.
  • 16. How to Use Internal Storage? • 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 object > Write to the file with write(). > Close the stream with close(). • To read a file from internal storage > Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. > Read bytes from the file with read(). > Then close the stream with close().
  • 17. Example: Using Internal Storage String FILENAME = "hello_file"; String string = "hello world!"; FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close();
  • 18. Other Useful Methods • 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.
  • 20. Using 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.
  • 21. Checking Media Availability • Before you do any work with the external storage, you should always call getExternalStorageState() to check the state of the media > Mounted > Missing > Read-only > Some other state
  • 22. Example: Checking Media State 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; }
  • 23. Accessing files on external storage (1) • If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files > This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES > This method will create the appropriate directory if necessary. > By specifying the type of directory, you ensure that the Android's media scanner will properly categorize your files in the system (for example, ringtones are identified as ringtones and not music). > If the user uninstalls your application, this directory and all its contents will be deleted.
  • 24. Accessing files on external storage (2) • If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in the following directory: > /Android/data/<package_name>/files/ (where <package_name> is your Java-style package name, such as "com.example.android.app")
  • 25. Saving Files that Should be Shared (1) • If you want to save files that are not specific to your application and that should not be deleted when your application is uninstalled, save them to one of the public directories on the external storage. > These directories lay at the root of the external storage, such as Music/, Pictures/, Ringtones/, and others.
  • 26. Saving Files that Should be Shared (2) • In API Level 8 or greater > Use getExternalStoragePublicDirectory(), passing it the type of public directory you want, such as DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES, or others. > This method will create the appropriate directory if necessary. • In API Level 7 or lower > Use getExternalStorageDirectory() to open a File that represents the root of the external storage, then save your shared files in one of the following directories: > Music/, Podcasts/, Ringtones/, Alarms/, Notifications/, Pictures/, Movies/, Download/
  • 28. Using Databases • Android provides full support for SQLite databases. > SQLite is a software library that implements a self- contained, serverless, zero-configuration, transactional SQL database engine. • Any databases you create will be accessible 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.
  • 29. Using Databases - Two Options • Option #1 > 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. > Then use execSQL() for executing SQL • Option #2 > Use openOrCreateDatabase() to create SQLiteDatabase > Then use execSQL() for executing SQL
  • 30. Option #1: Create Database & Table public class MyDbOpenHelper 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); } }
  • 31. Option #2: Creating Database & Table private static final String DATABASE_NAME = "myDB.db"; private static final String DATABASE_TABLE_NAME = "COUNTRY"; private static final String DATABASE_CREATE_TABLE = "create table " + DATABASE_TABLE_NAME + " (_id integer primary key autoincrement, " + " country_name text not null, " + " capital_city text not null)"; // Open a new private SQLiteDatabase associated with this Context's application // package. Create the database file if it doesn't exist. SQLiteDatabase myDB = openOrCreateDatabase( DATABASE_NAME, Context.MODE_PRIVATE, null); // Create database table myDB.execSQL(DATABASE_CREATE_TABLE);
  • 32. Example: Inserting a row SQLiteDatabase myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null); // Create a new row and insert it into the database. ContentValues newRow = new ContentValues(); newRow.put("country_name", "U.S.A."); newRow.put("capital_city", "Washington D.C."); myDB.insert(DATABASE_TABLE_NAME, null, newRow);
  • 33. Example: Retrieving all rows SQLiteDatabase myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null); // Select columns to retrieve in the form of String array String[] resultColumns = new String[] {"_id", "country_name", "capital_city"}; Cursor cursor = myDB.query(DATABASE_TABLE_NAME, resultColumns, null, null, null, null, null, null); String res = "Result is:"; Integer cindex = cursor.getColumnIndex("country_name"); if (cursor.moveToFirst()) { do { res += cursor.getString(cindex)+"-"; } while (cursor.moveToNext()); }