SlideShare une entreprise Scribd logo
1  sur  19
Android Data
Storage
Android Training
By Khaled Anaqwa
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.
SharedPreferences
 The SharedPreferences class provides a
general framework that allows you to
save and retrieve persistent key-value
pairs of primitive data types.
 This data will persist across user sessions
(even if your application is killed).
To work with shared
preferences you need to
 Initialization
 Storing Data
 Commit changes
 Retrieving Data
 Clearing / Deleting Data
Initialization
Application shared preferences can be fetched
using getSharedPreferences() method.
You also need an editor to edit and save the
changes in shared preferences.
SharedPreferences pref =
getApplicationContext().getSharedPreferences(”FileName", 0); // 0 - for
private mode
Editor editor = pref.edit();
Application shared preferences
can be fetched using
 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.
Storing Data
You can save data into shared preferences using editor. All the
primitive data types like booleans, floats, ints, longs, and strings
are supported.
You need to put data as Key with Value.
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
Commit changes
Call editor.commit() in order to save changes to shared
preferences..
like
editor.commit();
Retrieving Data
Data can be retrived from saved preferences by calling
getString() (For string) method.
Remember this method should be called on Shared Preferences
not on Editor.
// returns stored preference value
// If value is not present return default value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Clearing / Deleting Data
If you want to delete from shared preferences you can call
remove(“key_name”) to delete that particular value.
If you want to delete all the data, call clear().
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes;
editor.clear(); //clear all the data from shared preferences
editor.commit(); // commit changes
Task
 Create Settings with ShaerdPresferance
 General Settings
 Language selection
 Text Size
 Email
 Textcolor
 System Settings
 Enable Notifications
 use Wifi
 About
Using the 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.
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().
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos =
openFileOutput(FILENAME,Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.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().
RAW Files
 If you want to save a static file in your
application at compile time, save the file
in your project res/raw/ directory.
 You can open it with
openRawResource(), passing the
R.raw.<filename> resource ID.
 This method returns an InputStream that
you can use to read the file (but you
cannot write to the original file).
Cache Files:
 If you'd like to cache some data, rather
than store it persistently, you should use
getCacheDir() to open a File that
represents the internal directory where
your application should save temporary
cache files.
PreferenceActivity
 This is the base class for an activity to
show a hierarchy of preferences to the
user.
 this functionality should now be found in
the new PreferenceFragment class.
 using PreferenceActivity in its old mode,
the documentation there applies to the
deprecated APIs here.
Android Training (Storing & Shared Preferences)

Contenu connexe

Tendances

Android datastorage
Android datastorageAndroid datastorage
Android datastorage
Krazy Koder
 
android activity
android activityandroid activity
android activity
Deepa Rani
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 

Tendances (20)

SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
Broadcast Receivers in Android
Broadcast Receivers in AndroidBroadcast Receivers in Android
Broadcast Receivers in Android
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
android activity
android activityandroid activity
android activity
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)Singleton Pattern (Sole Object with Global Access)
Singleton Pattern (Sole Object with Global Access)
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
History Of JAVA
History Of JAVAHistory Of JAVA
History Of JAVA
 
7.data types in c#
7.data types in c#7.data types in c#
7.data types in c#
 
Adobe AEM - From Eventing to Job Processing
Adobe AEM - From Eventing to Job ProcessingAdobe AEM - From Eventing to Job Processing
Adobe AEM - From Eventing to Job Processing
 
Android adapters
Android adaptersAndroid adapters
Android adapters
 
Simple xml in .net
Simple xml in .netSimple xml in .net
Simple xml in .net
 
Android resources
Android resourcesAndroid resources
Android resources
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycle
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
05 intent
05 intent05 intent
05 intent
 

En vedette

Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
Ahsanul Karim
 

En vedette (20)

Android Training (Content Provider)
Android Training (Content Provider)Android Training (Content Provider)
Android Training (Content Provider)
 
Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
 
Android Fragment Pattern: Communication
Android Fragment Pattern: CommunicationAndroid Fragment Pattern: Communication
Android Fragment Pattern: Communication
 
Android 101 - Introduction to Android Development
Android 101 - Introduction to Android DevelopmentAndroid 101 - Introduction to Android Development
Android 101 - Introduction to Android Development
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment Communication
 
iOS course day 1
iOS course day 1iOS course day 1
iOS course day 1
 
iOS Course day 2
iOS Course day 2iOS Course day 2
iOS Course day 2
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
 
INSTALACIÓN ANDROID STUDIO 2
INSTALACIÓN ANDROID STUDIO 2INSTALACIÓN ANDROID STUDIO 2
INSTALACIÓN ANDROID STUDIO 2
 
Android UI Testing with uiautomator
Android UI Testing with uiautomatorAndroid UI Testing with uiautomator
Android UI Testing with uiautomator
 
Android complete basic Guide
Android complete basic GuideAndroid complete basic Guide
Android complete basic Guide
 
Android - Working with Fragments
Android - Working with FragmentsAndroid - Working with Fragments
Android - Working with Fragments
 
Screen orientations in android
Screen orientations in androidScreen orientations in android
Screen orientations in android
 
Mobile design matters - iOS and Android
Mobile design matters - iOS and AndroidMobile design matters - iOS and Android
Mobile design matters - iOS and Android
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
Android Training (android fundamental)
Android Training (android fundamental)Android Training (android fundamental)
Android Training (android fundamental)
 
Android training (android style)
Android training (android style)Android training (android style)
Android training (android style)
 
Android Training (Broadcast Receiver)
Android Training (Broadcast Receiver)Android Training (Broadcast Receiver)
Android Training (Broadcast Receiver)
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
 
Android Training (Touch)
Android Training (Touch)Android Training (Touch)
Android Training (Touch)
 

Similaire à Android Training (Storing & Shared Preferences)

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
 
03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)
TECOS
 
WP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows PhoneWP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows Phone
MICTT Palma
 
Question IYou are going to use the semaphores for process sy.docx
Question IYou are going to use the semaphores for process sy.docxQuestion IYou are going to use the semaphores for process sy.docx
Question IYou are going to use the semaphores for process sy.docx
audeleypearl
 

Similaire à Android Training (Storing & Shared Preferences) (20)

Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
Android-data storage in android-chapter21
Android-data storage in android-chapter21Android-data storage in android-chapter21
Android-data storage in android-chapter21
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 Storage
 
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
 
Level 4
Level 4Level 4
Level 4
 
Data management
Data managementData management
Data management
 
Data management
Data managementData management
Data management
 
Memory management
Memory managementMemory management
Memory management
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
 
Android Workshop 2013
Android Workshop 2013Android Workshop 2013
Android Workshop 2013
 
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
 
03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)03 programmation mobile - android - (stockage, multithreads, web services)
03 programmation mobile - android - (stockage, multithreads, web services)
 
Data Storage
Data StorageData Storage
Data Storage
 
WP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows PhoneWP7 HUB_Creando aplicaciones de Windows Phone
WP7 HUB_Creando aplicaciones de Windows Phone
 
Slice for Distributed Persistence (JavaOne 2010)
Slice for Distributed Persistence (JavaOne 2010)Slice for Distributed Persistence (JavaOne 2010)
Slice for Distributed Persistence (JavaOne 2010)
 
Techniques for Cross Platform .NET Development
Techniques for Cross Platform .NET DevelopmentTechniques for Cross Platform .NET Development
Techniques for Cross Platform .NET Development
 
Storage 8
Storage   8Storage   8
Storage 8
 
Question IYou are going to use the semaphores for process sy.docx
Question IYou are going to use the semaphores for process sy.docxQuestion IYou are going to use the semaphores for process sy.docx
Question IYou are going to use the semaphores for process sy.docx
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
 
12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx
 

Plus de Khaled Anaqwa (9)

Android Training (Notifications)
Android Training (Notifications)Android Training (Notifications)
Android Training (Notifications)
 
Android Training (Animation)
Android Training (Animation)Android Training (Animation)
Android Training (Animation)
 
Android Training (Sensors)
Android Training (Sensors)Android Training (Sensors)
Android Training (Sensors)
 
Android Training (Media)
Android Training (Media)Android Training (Media)
Android Training (Media)
 
Android Training (AdapterView & Adapter)
Android Training (AdapterView & Adapter)Android Training (AdapterView & Adapter)
Android Training (AdapterView & Adapter)
 
Android Training (ScrollView , Horizontal ScrollView WebView)
Android Training (ScrollView , Horizontal ScrollView  WebView)Android Training (ScrollView , Horizontal ScrollView  WebView)
Android Training (ScrollView , Horizontal ScrollView WebView)
 
Android Training (Android UI)
Android Training (Android UI)Android Training (Android UI)
Android Training (Android UI)
 
Android Training (Intro)
Android Training (Intro)Android Training (Intro)
Android Training (Intro)
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Android Training (Storing & Shared Preferences)

  • 2. 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.
  • 3. SharedPreferences  The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types.  This data will persist across user sessions (even if your application is killed).
  • 4. To work with shared preferences you need to  Initialization  Storing Data  Commit changes  Retrieving Data  Clearing / Deleting Data
  • 5. Initialization Application shared preferences can be fetched using getSharedPreferences() method. You also need an editor to edit and save the changes in shared preferences. SharedPreferences pref = getApplicationContext().getSharedPreferences(”FileName", 0); // 0 - for private mode Editor editor = pref.edit();
  • 6. Application shared preferences can be fetched using  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.
  • 7. Storing Data You can save data into shared preferences using editor. All the primitive data types like booleans, floats, ints, longs, and strings are supported. You need to put data as Key with Value. editor.putBoolean("key_name", true); // Storing boolean - true/false editor.putString("key_name", "string value"); // Storing string editor.putInt("key_name", "int value"); // Storing integer editor.putFloat("key_name", "float value"); // Storing float editor.putLong("key_name", "long value"); // Storing long
  • 8. Commit changes Call editor.commit() in order to save changes to shared preferences.. like editor.commit();
  • 9. Retrieving Data Data can be retrived from saved preferences by calling getString() (For string) method. Remember this method should be called on Shared Preferences not on Editor. // returns stored preference value // If value is not present return default value - In this case null pref.getString("key_name", null); // getting String pref.getInt("key_name", null); // getting Integer pref.getFloat("key_name", null); // getting Float pref.getLong("key_name", null); // getting Long pref.getBoolean("key_name", null); // getting boolean
  • 10. Clearing / Deleting Data If you want to delete from shared preferences you can call remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear(). editor.remove("name"); // will delete key name editor.remove("email"); // will delete key email editor.commit(); // commit changes; editor.clear(); //clear all the data from shared preferences editor.commit(); // commit changes
  • 11. Task  Create Settings with ShaerdPresferance  General Settings  Language selection  Text Size  Email  Textcolor  System Settings  Enable Notifications  use Wifi  About
  • 12. Using the 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.
  • 13. 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().
  • 14. String FILENAME = "hello_file"; String string = "hello world!"; FileOutputStream fos = openFileOutput(FILENAME,Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close();
  • 15. 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().
  • 16. RAW Files  If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory.  You can open it with openRawResource(), passing the R.raw.<filename> resource ID.  This method returns an InputStream that you can use to read the file (but you cannot write to the original file).
  • 17. Cache Files:  If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should save temporary cache files.
  • 18. PreferenceActivity  This is the base class for an activity to show a hierarchy of preferences to the user.  this functionality should now be found in the new PreferenceFragment class.  using PreferenceActivity in its old mode, the documentation there applies to the deprecated APIs here.