SlideShare a Scribd company logo
l

Persistence
l

l

l

Persistence

Three ways to store data
l Shared Preferences
l Files
l SQLite databases
Mechanism to store/access private data
l Content Providers
l

l

Shared Preferences

Three forms:
l

Share across all components in an application

l

getSharedPreferences(“SomeString”,Activity.MODE_PRIVATE);

l

Store only data needed by this Activity

l

l
l
l

getPreferences(Activity.MODE_PRIVATE);

Store only data needed by this Activity when Activity becomes
inactive (but not when finished)
Ex. Orientation change from portrait to landscape
use Bundle in onSaveInstanceState/onRestoreInstanceState/onCreate
l
l

Shared Preferences

Across all components
• public static final String CMPREFS = "CampusMapSharedPreferences";
•
•
•
•
•
•
•
•
•
•
•
•
•
•

private void savePreferences() {
SharedPreferences cmSharedPreferences =
getSharedPreferences(CMPREFS,Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = cmSharedPreferences.edit();
editor.putBoolean(VIRTUAL_MODE, inVirtualMode);
editor.putInt(MAP_INDEX, curMapIndex);
editor.commit();
}
private void restoreUIState() {
SharedPreferences cmSharedPreferences =
getSharedPreferences(CMPREFS,Activity.MODE_PRIVATE);
inVirtualMode = cmSharedPreferences.getBoolean(VIRTUAL_MODE, true);
curMapIndex = cmSharedPreferences.getInt(MAP_INDEX, 0);
}
l
l

Shared Preferences

Only for this Activity (each Activity has one)
•
•
•
•
•
•
•
•
•
•
•
•
•
•

private void savePreferences() {
SharedPreferences cmActivityPreferences =
getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = cmActivityPreferences.edit();
editor.putBoolean(VIRTUAL_MODE, inVirtualMode);
editor.putInt(MAP_INDEX, curMapIndex);
editor.commit();
}
private void restoreUIState() {
SharedPreferences cmActivityPreferences =
getPreferences(Activity.MODE_PRIVATE);
inVirtualMode = cmActivityPreferences.getBoolean(VIRTUAL_MODE, true);
curMapIndex = cmActivityPreferences.getInt(MAP_INDEX, 0);
}
l
l

Shared Preferences

Only for this Activity when inactive/active
l Note: onSaveInstanceState called when an Activity becomes
inactive, not when closed by finish() or user pressing back button

• public static final String TEXTVIEW_STATE_KEY = “TEXTVIEW_STATE_KEY";
•
•
•
•
•
•
•
•
•
•
•

private void onSaveInstanceState(Bundle outState) {
outState.putString(TEXTVIEW_STATE_KEY,
(TextView)findViewById(R.id.myTextView).getText().toString());
super.onSaveInstanceState(outState);
}
private void onRestoreInstanceState(Bundle inState) { //same for onCreate()
if(inState != null && inState.containsKey(TEXTVIEW_STATE_KEY)) {
(TextView)findViewById(R.id.myTextView).
setText(inState.getString(TEXTVIEW_STATE_KEY));
}
}
l
l
l

Files

Generally not recommended to use files
Store read-only static files in res/raw

• InputStream myFile =
getResources().openRawResource(R.raw.myfilename);
l
l
l

Files

Generally not recommended to use files
Store read-only static files in res/raw

• InputStream myFile =
getResources().openRawResource(R.raw.myfilename);
l
l
l

Files

Standard java.io is available
Can also use openFileOutput and openFileInput

• byte[] b = new String("Yo").getBytes();
• Also available:
• Context.MODE_PRIVATE
• try {
• Context.MODE_WORLD_READABLE
•
FileOutputStream fos =
•
openFileOutput("anotherExampleFile.txt",
•
Context.MODE_WORLD_WRITEABLE);
•
fos.write(b);
•
FileInputStream fis =
•
openFileInput("anotherExampleFile.txt");
•
fis.read(b);
• } catch (IOException e) {}
l

l

l
l

l

SQLite Databases

RDBMS provided through a library so it becomes part of
your app
Use the SQL you learned in database course
Use Db best practices
l Normalize data
l Encapsulate db info in helper or wrapper classes
Don’t store files (e.g. images or audio)
l Instead store the path string
l

Creating a Database

• SQLiteDatabase myDb =
•
openOrCreateDatabase("example.db",
•
Context.MODE_PRIVATE,
•
null); //optional CursorFactory
• myDb.execSQL("drop table if exists jokeTable");
• myDb.execSQL("create table jokeTable " +
•
" ( _id integer primary key autoincrement," +
•
"author text not null, joke text not null);");
l

l

l

•
•
•
•

Inserting Data

ContentValues are key/value pairs that are used when
inserting/updating databases
Each ContentValue object corresponds to one row in a table

ContentValues newValues = new ContentValues();
newValues.put("author", "David Janzen");
newValues.put("joke", "This is a joke");
myDb.insert("jokeTable",null,newValues);
l

Updating Data

• ContentValues updatedValues = new ContentValues();
• updatedValues.put("joke", "This is a better joke");
• myDb.update("jokeTable",
•
updatedValues,
•
"author='David Janzen'", //where clause
•
null);
//whereArgs
l

•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

Querying Data with query()

Cursor jokes = myDb.query("jokeTable",
null, //columns
null, //where clause
null, //args if ? in where clause
null, //groupBy
null, //having
null); //orderBy
if (jokes.moveToFirst()) {
do {
String author = jokes.getString(1);
String joke = jokes.getString(2);
((TextView)findViewById(R.id.hello)).setText(author +
": " + joke);
} while(jokes.moveToNext());
}
l

l
l
l
l
l
l
l

Other Cursor Functions

moveToPrevious
getCount
getColumnIndexOrThrow
getColumnName
getColumnNames
moveToPosition
getPosition
l

Deleting Data

• myDb.delete("jokeTable",
•
"author='David Janzen'",
•
null);
l

l

l
l

Content Providers

Apps can expose their data layer through a Content Provider,
identified by a URI
Some native apps provide Content Providers
Your apps can provide Content Providers
l
l

•
•
•
•
•
•
•
•
•
•
•
•

Content Resolver

Each application Context has a single ContentResolver that
can be used to access a Content Provider
• URI,colums,where,whereArgs,orderBy

Cursor allRows = getContentResolver().query(
People.CONTENT_URI, null, null, null, null);
startManagingCursor(allRows);
int nameIdx = allRows.getColumnIndexOrThrow(People.NAME);
int phoneIdx = allRows.getColumnIndexOrThrow(People.NUMBER);
if (allRows.moveToFirst()) {
do {
String name = allRows.getString(nameIdx);
String number = allRows.getString(phoneIdx);
//do something with name and number
} while(allRows.moveToNext());
}

• Requires: <uses-permission android:name="android.permission.READ_CONTACTS" />
l
l

Insert, Update, Delete

Similar to SQLiteDatabase

•
•
•
•
•

SQLiteDatabase myDb = openOrCreateDatabase(…);
ContentValues newValues = new ContentValues();
newValues.put("author", "David Janzen");
newValues.put("joke", "This is a joke");
myDb.insert("jokeTable",null,newValues);

•
•
•
•
•
•
•

ContentValues newValues = new ContentValues();
l
Update and Delete are similar
newValues.put("author", "David Janzen");
newValues.put("joke", "This is a joke");
getContentResolver().insert(MY_CONTENT_URI, newValues);
//or
//ContentValues[] valueArray = new ContentValues[10];
//getContentResolver().bulkInsert(MY_CONTENT_URI, valueArray);
l

Creating Your Own Content Provider

• public class MapProvider extends ContentProvider {
• private static final String mapURI =
•
“content://com.simexusa.provider.campusmaps/maps”;
• public static final Uri CONTENT_URI = Uri.parse(mapURI);
• @Override public boolean onCreate() {
•
//create the database and tables
• }
• //handle both forms of Content URIs (…/maps or …/maps/3 for third one)
• private static final int ALLROWS = 1;
• private static final int SINGLE_ROW = 2;
• private static final UriMatcher uriMatcher;
• static {
•
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
•
uriMatcher.addURI(“com.simexusa.provider.campusmaps”,”maps”,ALLROWS);
•
uriMatcher.addURI(“com.simexusa.provider.campusmaps”,”maps/#”,SINGLE_ROW);
• }
• }
l

Provide query, insert, delete, update

• @Override public Cursor query(Uri uri, String[] projection, String selection,
•
String[] selectionArgs, String sort) {
•
switch (uriMatcher.match(uri)) {
•
case SINGLE_ROW :
•
…
•
case ALLROWS :
•
…
•
default: :
•
…
•
}
•
return null;
• }
l

getType() and manifest

• @Override public String getType(Uri uri) {
•
switch (uriMatcher.match(uri)) {
•
case SINGLE_ROW :
•
return “vnd.simexusa.cursor.item/mapprovider”;
•
case ALLROWS :
•
l return “vnd.simexusa.cursor.dir/mapprovider”;
In ApplicationManifest.xml
•
default: :
•
throw new IllegalArgumentException(“Unsupported URI: “ + uri);
•
}
• }

• <provider android:name=“MapProvider”
•
android:authorities=“com.simexusa.provider.campusmap” />

More Related Content

What's hot

[Android] Data Storage
[Android] Data Storage[Android] Data Storage
[Android] Data Storage
Nikmesoft Ltd
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
John David Duncan
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
John David Duncan
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
Sourabh Sahu
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
chhaichivon
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
Ivano Malavolta
 
Local Storage
Local StorageLocal Storage
Local Storage
Ivano Malavolta
 
Web scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabsWeb scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabs
zekeLabs Technologies
 
Mysql all
Mysql allMysql all
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
Nguyen Tuan
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
info_zybotech
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
Knoldus Inc.
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
jeromevdl
 
Oak Lucene Indexes
Oak Lucene IndexesOak Lucene Indexes
Oak Lucene Indexes
Chetan Mehrotra
 
Sequelize
SequelizeSequelize
Sequelize
Tarek Raihan
 
Hive commands
Hive commandsHive commands
Hive commands
Ganesh Sanap
 
Drupal 7 database api
Drupal 7 database api Drupal 7 database api
Drupal 7 database api
Andrii Podanenko
 
REST Basics
REST BasicsREST Basics
REST Basics
Ivano Malavolta
 

What's hot (20)

[Android] Data Storage
[Android] Data Storage[Android] Data Storage
[Android] Data Storage
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Local Storage
Local StorageLocal Storage
Local Storage
 
Web scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabsWeb scraping using scrapy - zekeLabs
Web scraping using scrapy - zekeLabs
 
Mysql all
Mysql allMysql all
Mysql all
 
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
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
 
Oak Lucene Indexes
Oak Lucene IndexesOak Lucene Indexes
Oak Lucene Indexes
 
Sequelize
SequelizeSequelize
Sequelize
 
Hive commands
Hive commandsHive commands
Hive commands
 
Drupal 7 database api
Drupal 7 database api Drupal 7 database api
Drupal 7 database api
 
REST Basics
REST BasicsREST Basics
REST Basics
 

Viewers also liked

Map
MapMap
Deployment
DeploymentDeployment
Deployment
Training Guide
 
Getting started
Getting startedGetting started
Getting started
Training Guide
 
Application lifecycle
Application lifecycleApplication lifecycle
Application lifecycle
Training Guide
 
Infinum Android Talks #04 - Google Maps Android API utility library
Infinum Android Talks #04 - Google Maps Android API utility libraryInfinum Android Talks #04 - Google Maps Android API utility library
Infinum Android Talks #04 - Google Maps Android API utility library
Denis_infinum
 
Android application for gps
Android application for gpsAndroid application for gps
Android application for gps
Sutej Chakka
 

Viewers also liked (6)

Map
MapMap
Map
 
Deployment
DeploymentDeployment
Deployment
 
Getting started
Getting startedGetting started
Getting started
 
Application lifecycle
Application lifecycleApplication lifecycle
Application lifecycle
 
Infinum Android Talks #04 - Google Maps Android API utility library
Infinum Android Talks #04 - Google Maps Android API utility libraryInfinum Android Talks #04 - Google Maps Android API utility library
Infinum Android Talks #04 - Google Maps Android API utility library
 
Android application for gps
Android application for gpsAndroid application for gps
Android application for gps
 

Similar to Persistences

Android Lab Test : Reading the foot file list (english)
Android Lab Test : Reading the foot file list (english)Android Lab Test : Reading the foot file list (english)
Android Lab Test : Reading the foot file list (english)
Bruno Delb
 
Get docs from sp doc library
Get docs from sp doc libraryGet docs from sp doc library
Get docs from sp doc library
Sudip Sengupta
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
Ismail Mayat
 
Android Database
Android DatabaseAndroid Database
Android Database
Dr Karthikeyan Periasamy
 
Big data, just an introduction to Hadoop and Scripting Languages
Big data, just an introduction to Hadoop and Scripting LanguagesBig data, just an introduction to Hadoop and Scripting Languages
Big data, just an introduction to Hadoop and Scripting Languages
Corley S.r.l.
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes Workshop
Erik Hatcher
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science Bootcamp
Kais Hassan, PhD
 
Wiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programmingWiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programming
AnalyticsConf
 
OOP Adventures with XOOPS
OOP Adventures with XOOPSOOP Adventures with XOOPS
OOP Adventures with XOOPS
xoopsproject
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring Data
Eric Bottard
 
Moose
MooseMoose
04 darwino concepts and utility classes
04   darwino concepts and utility classes04   darwino concepts and utility classes
04 darwino concepts and utility classes
darwinodb
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
Osman Yuksel
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 Flow
Karsten Dambekalns
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
James Johnson
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
Gabriele Lana
 
Modules Building Presentation
Modules Building PresentationModules Building Presentation
Modules Building Presentation
htyson
 
Power tools in Java
Power tools in JavaPower tools in Java
Power tools in Java
DPC Consulting Ltd
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
ssuser0562f1
 
Building a Search Engine Using Lucene
Building a Search Engine Using LuceneBuilding a Search Engine Using Lucene
Building a Search Engine Using Lucene
Abdelrahman Othman Helal
 

Similar to Persistences (20)

Android Lab Test : Reading the foot file list (english)
Android Lab Test : Reading the foot file list (english)Android Lab Test : Reading the foot file list (english)
Android Lab Test : Reading the foot file list (english)
 
Get docs from sp doc library
Get docs from sp doc libraryGet docs from sp doc library
Get docs from sp doc library
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
 
Android Database
Android DatabaseAndroid Database
Android Database
 
Big data, just an introduction to Hadoop and Scripting Languages
Big data, just an introduction to Hadoop and Scripting LanguagesBig data, just an introduction to Hadoop and Scripting Languages
Big data, just an introduction to Hadoop and Scripting Languages
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes Workshop
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science Bootcamp
 
Wiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programmingWiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programming
 
OOP Adventures with XOOPS
OOP Adventures with XOOPSOOP Adventures with XOOPS
OOP Adventures with XOOPS
 
Hands On Spring Data
Hands On Spring DataHands On Spring Data
Hands On Spring Data
 
Moose
MooseMoose
Moose
 
04 darwino concepts and utility classes
04   darwino concepts and utility classes04   darwino concepts and utility classes
04 darwino concepts and utility classes
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 Flow
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 
Modules Building Presentation
Modules Building PresentationModules Building Presentation
Modules Building Presentation
 
Power tools in Java
Power tools in JavaPower tools in Java
Power tools in Java
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
 
Building a Search Engine Using Lucene
Building a Search Engine Using LuceneBuilding a Search Engine Using Lucene
Building a Search Engine Using Lucene
 

Recently uploaded

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
maazsz111
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 

Recently uploaded (20)

Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 

Persistences

  • 2. l l l Persistence Three ways to store data l Shared Preferences l Files l SQLite databases Mechanism to store/access private data l Content Providers
  • 3. l l Shared Preferences Three forms: l Share across all components in an application l getSharedPreferences(“SomeString”,Activity.MODE_PRIVATE); l Store only data needed by this Activity l l l l getPreferences(Activity.MODE_PRIVATE); Store only data needed by this Activity when Activity becomes inactive (but not when finished) Ex. Orientation change from portrait to landscape use Bundle in onSaveInstanceState/onRestoreInstanceState/onCreate
  • 4. l l Shared Preferences Across all components • public static final String CMPREFS = "CampusMapSharedPreferences"; • • • • • • • • • • • • • • private void savePreferences() { SharedPreferences cmSharedPreferences = getSharedPreferences(CMPREFS,Activity.MODE_PRIVATE); SharedPreferences.Editor editor = cmSharedPreferences.edit(); editor.putBoolean(VIRTUAL_MODE, inVirtualMode); editor.putInt(MAP_INDEX, curMapIndex); editor.commit(); } private void restoreUIState() { SharedPreferences cmSharedPreferences = getSharedPreferences(CMPREFS,Activity.MODE_PRIVATE); inVirtualMode = cmSharedPreferences.getBoolean(VIRTUAL_MODE, true); curMapIndex = cmSharedPreferences.getInt(MAP_INDEX, 0); }
  • 5. l l Shared Preferences Only for this Activity (each Activity has one) • • • • • • • • • • • • • • private void savePreferences() { SharedPreferences cmActivityPreferences = getPreferences(Activity.MODE_PRIVATE); SharedPreferences.Editor editor = cmActivityPreferences.edit(); editor.putBoolean(VIRTUAL_MODE, inVirtualMode); editor.putInt(MAP_INDEX, curMapIndex); editor.commit(); } private void restoreUIState() { SharedPreferences cmActivityPreferences = getPreferences(Activity.MODE_PRIVATE); inVirtualMode = cmActivityPreferences.getBoolean(VIRTUAL_MODE, true); curMapIndex = cmActivityPreferences.getInt(MAP_INDEX, 0); }
  • 6. l l Shared Preferences Only for this Activity when inactive/active l Note: onSaveInstanceState called when an Activity becomes inactive, not when closed by finish() or user pressing back button • public static final String TEXTVIEW_STATE_KEY = “TEXTVIEW_STATE_KEY"; • • • • • • • • • • • private void onSaveInstanceState(Bundle outState) { outState.putString(TEXTVIEW_STATE_KEY, (TextView)findViewById(R.id.myTextView).getText().toString()); super.onSaveInstanceState(outState); } private void onRestoreInstanceState(Bundle inState) { //same for onCreate() if(inState != null && inState.containsKey(TEXTVIEW_STATE_KEY)) { (TextView)findViewById(R.id.myTextView). setText(inState.getString(TEXTVIEW_STATE_KEY)); } }
  • 7. l l l Files Generally not recommended to use files Store read-only static files in res/raw • InputStream myFile = getResources().openRawResource(R.raw.myfilename);
  • 8. l l l Files Generally not recommended to use files Store read-only static files in res/raw • InputStream myFile = getResources().openRawResource(R.raw.myfilename);
  • 9. l l l Files Standard java.io is available Can also use openFileOutput and openFileInput • byte[] b = new String("Yo").getBytes(); • Also available: • Context.MODE_PRIVATE • try { • Context.MODE_WORLD_READABLE • FileOutputStream fos = • openFileOutput("anotherExampleFile.txt", • Context.MODE_WORLD_WRITEABLE); • fos.write(b); • FileInputStream fis = • openFileInput("anotherExampleFile.txt"); • fis.read(b); • } catch (IOException e) {}
  • 10. l l l l l SQLite Databases RDBMS provided through a library so it becomes part of your app Use the SQL you learned in database course Use Db best practices l Normalize data l Encapsulate db info in helper or wrapper classes Don’t store files (e.g. images or audio) l Instead store the path string
  • 11. l Creating a Database • SQLiteDatabase myDb = • openOrCreateDatabase("example.db", • Context.MODE_PRIVATE, • null); //optional CursorFactory • myDb.execSQL("drop table if exists jokeTable"); • myDb.execSQL("create table jokeTable " + • " ( _id integer primary key autoincrement," + • "author text not null, joke text not null);");
  • 12. l l l • • • • Inserting Data ContentValues are key/value pairs that are used when inserting/updating databases Each ContentValue object corresponds to one row in a table ContentValues newValues = new ContentValues(); newValues.put("author", "David Janzen"); newValues.put("joke", "This is a joke"); myDb.insert("jokeTable",null,newValues);
  • 13. l Updating Data • ContentValues updatedValues = new ContentValues(); • updatedValues.put("joke", "This is a better joke"); • myDb.update("jokeTable", • updatedValues, • "author='David Janzen'", //where clause • null); //whereArgs
  • 14. l • • • • • • • • • • • • • • • Querying Data with query() Cursor jokes = myDb.query("jokeTable", null, //columns null, //where clause null, //args if ? in where clause null, //groupBy null, //having null); //orderBy if (jokes.moveToFirst()) { do { String author = jokes.getString(1); String joke = jokes.getString(2); ((TextView)findViewById(R.id.hello)).setText(author + ": " + joke); } while(jokes.moveToNext()); }
  • 17. l l l l Content Providers Apps can expose their data layer through a Content Provider, identified by a URI Some native apps provide Content Providers Your apps can provide Content Providers
  • 18. l l • • • • • • • • • • • • Content Resolver Each application Context has a single ContentResolver that can be used to access a Content Provider • URI,colums,where,whereArgs,orderBy Cursor allRows = getContentResolver().query( People.CONTENT_URI, null, null, null, null); startManagingCursor(allRows); int nameIdx = allRows.getColumnIndexOrThrow(People.NAME); int phoneIdx = allRows.getColumnIndexOrThrow(People.NUMBER); if (allRows.moveToFirst()) { do { String name = allRows.getString(nameIdx); String number = allRows.getString(phoneIdx); //do something with name and number } while(allRows.moveToNext()); } • Requires: <uses-permission android:name="android.permission.READ_CONTACTS" />
  • 19. l l Insert, Update, Delete Similar to SQLiteDatabase • • • • • SQLiteDatabase myDb = openOrCreateDatabase(…); ContentValues newValues = new ContentValues(); newValues.put("author", "David Janzen"); newValues.put("joke", "This is a joke"); myDb.insert("jokeTable",null,newValues); • • • • • • • ContentValues newValues = new ContentValues(); l Update and Delete are similar newValues.put("author", "David Janzen"); newValues.put("joke", "This is a joke"); getContentResolver().insert(MY_CONTENT_URI, newValues); //or //ContentValues[] valueArray = new ContentValues[10]; //getContentResolver().bulkInsert(MY_CONTENT_URI, valueArray);
  • 20. l Creating Your Own Content Provider • public class MapProvider extends ContentProvider { • private static final String mapURI = • “content://com.simexusa.provider.campusmaps/maps”; • public static final Uri CONTENT_URI = Uri.parse(mapURI); • @Override public boolean onCreate() { • //create the database and tables • } • //handle both forms of Content URIs (…/maps or …/maps/3 for third one) • private static final int ALLROWS = 1; • private static final int SINGLE_ROW = 2; • private static final UriMatcher uriMatcher; • static { • uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); • uriMatcher.addURI(“com.simexusa.provider.campusmaps”,”maps”,ALLROWS); • uriMatcher.addURI(“com.simexusa.provider.campusmaps”,”maps/#”,SINGLE_ROW); • } • }
  • 21. l Provide query, insert, delete, update • @Override public Cursor query(Uri uri, String[] projection, String selection, • String[] selectionArgs, String sort) { • switch (uriMatcher.match(uri)) { • case SINGLE_ROW : • … • case ALLROWS : • … • default: : • … • } • return null; • }
  • 22. l getType() and manifest • @Override public String getType(Uri uri) { • switch (uriMatcher.match(uri)) { • case SINGLE_ROW : • return “vnd.simexusa.cursor.item/mapprovider”; • case ALLROWS : • l return “vnd.simexusa.cursor.dir/mapprovider”; In ApplicationManifest.xml • default: : • throw new IllegalArgumentException(“Unsupported URI: “ + uri); • } • } • <provider android:name=“MapProvider” • android:authorities=“com.simexusa.provider.campusmap” />