SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Downloaden Sie, um offline zu lesen
Saving Data
How to save your application data in your device
+RobertoOrgiu
@_tiwiz
+MatteoBonifazi
@mbonifazi
Storage options
Android provides several options for you to save
persistent application data.
Saving Key-Value Sets
With relatively small collection of key-values
that you'd like to save, you should use the
SharedPreferences APIs
Handle to a SharedPreferences
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
getSharedPreferences() multiple shared
preference files identified by name, which you
specify with the first parameter. You can call
this from any Context in your app.
getPreferences() use only one shared preference file for the
activity. Because this retrieves a default shared preference file
that belongs to the activity, you don't need to supply a name.
Write to Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read from Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Saving files
Internal or External Storage
All Android devices have two file storage areas: "internal"
and "external" storage.
Some devices divide the permanent storage space into
"internal" and "external" partitions, so even without a
removable storage medium
Internal Storage
Internal storage is best when you want to be sure
that neither the user nor other apps can access
your files.
● It's always available.
● Files saved here are accessible by only your app.
● When the user uninstalls your app, the system removes all
your app's files from internal storage.
Create a file in Local Storage
File file = new File(context.getFilesDir(), "myfile");
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput("myfile", Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
External Storage
The best place for files that don't require access
restrictions
● It's not always available.
● It's world-readable.
● When the user uninstalls your app, the system removes
your app's files from here only if you save them in the
directory from getExternalFilesDir().
Permission and Check Availability
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
Saving Data in SQL Databases
SQLite is a opensource SQL database that stores data to a
text file on a device. Android comes in with built in SQLite
database implementation.
SQLite supports all the relational database features. In order
to access this database, you don't need to establish any
kind of connections for it like JDBC,ODBC, e.t.c
The Contract class
public final class FeedReaderContract {
// To prevent someone from accidentally instantiating the contract class,
// make the constructor private.
private FeedReaderContract() {}
/* Inner class that defines the table contents */
public static class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_SUBTITLE = "subtitle";
}
}
A contract class is a container for constants that
define names for URIs, tables, and columns. The
contract class allows you to use the same constants
across all the other classes in the same package.
The Contract class
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
FeedEntry._ID + " INTEGER PRIMARY KEY," +
FeedEntry.COLUMN_NAME_TITLE + " TEXT," +
FeedEntry.COLUMN_NAME_SUBTITLE + " TEXT)";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
SQLiteOpenHelper
public class FeedReaderDbHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES);}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES); onCreate(db);
}
….
}
A useful set of APIs is available in the
SQLiteOpenHelper class. When you use this
class to obtain references to your database
Put Information into a Database
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle);
// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);
Read Information from a Database ( 1 / 2 )
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
String[] projection = { FeedEntry._ID, FeedEntry.COLUMN_NAME_TITLE,
FeedEntry.COLUMN_NAME_SUBTITLE };
String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" }; // Filter results WHERE "title" = 'My Title'
String sortOrder = FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor cursor = db.query/ FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder ); // The sort order
Read Information from a Database ( 2 / 2 )
List itemIds = new ArrayList<>();
while(cursor.moveToNext()) {
long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(FeedEntry._ID));
itemIds.add(itemId);
}
cursor.close();
Going forward
Youtube Video
https://www.youtube.com/watch?v=_vQaOvPsLko
https://www.youtube.com/watch?v=cp2rL3sAFmI
Reference Link
https://developer.android.com/training/basics/data-storage/shared-preferences.html
https://developer.android.com/training/basics/data-storage/files.html
https://developer.android.com/training/basics/data-storage/databases.html
There is no ONE SOLUTION!
But there are many other ways
ObjectBox
Website and reference
http://greenrobot.org/announcement/introducing-objectbox-beta/
http://greenrobot.org/objectbox/documentation/how-to-get-started/
Defining objects
@Entity
public class Note {
@Id
private long id;
private String text;
private Date date;
...
Obtaining a box
notesBox = ((MyApplication) getApplication()).getBoxStore().boxFor(Note.class);
Inserting notes
Note note = new Note(0, noteText, comment, new Date());
notesBox.put(note);
Log.d(App.TAG, "Inserted new note, ID: " + note.getId());
Removing notes
notesBox.remove(note);
Configuring the box
//MyApplication.java
boxStore = MyObjectBox.builder().androidContext(App.this).build();
More features
● Relations
● Compatibility with GreenDAO
● Queries
● Custom Types
+MatteoBonifazi
@mbonifazi
Thank You!
+RobertoOrgiu
@_tiwiz

Weitere ähnliche Inhalte

Was ist angesagt?

Architecture Components
Architecture Components Architecture Components
Architecture Components DataArt
 
Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1Kevin Octavian
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsAhsanul Karim
 
That’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your BatteryThat’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your BatteryMichael Galpin
 
Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Ryosuke Uchitate
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applicationsAlex Golesh
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsDiego Grancini
 
05 content providers - Android
05   content providers - Android05   content providers - Android
05 content providers - AndroidWingston
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorialinfo_zybotech
 
Data Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesData Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesArvind Krishnaa
 
Salesforce, APEX Concepts
Salesforce, APEX ConceptsSalesforce, APEX Concepts
Salesforce, APEX ConceptsGaurish Goel
 
Apache Struts 2 Advance
Apache Struts 2 AdvanceApache Struts 2 Advance
Apache Struts 2 AdvanceEmprovise
 
Wicket Security Presentation
Wicket Security PresentationWicket Security Presentation
Wicket Security Presentationmrmean
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sqlsaritasingh19866
 

Was ist angesagt? (18)

Architecture Components
Architecture Components Architecture Components
Architecture Components
 
Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
 
That’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your BatteryThat’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your Battery
 
Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門Form認証で学ぶSpring Security入門
Form認証で学ぶSpring Security入門
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applications
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layouts
 
05 content providers - Android
05   content providers - Android05   content providers - Android
05 content providers - Android
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Data Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesData Binding and Data Grid View Classes
Data Binding and Data Grid View Classes
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Salesforce, APEX Concepts
Salesforce, APEX ConceptsSalesforce, APEX Concepts
Salesforce, APEX Concepts
 
Apache Struts 2 Advance
Apache Struts 2 AdvanceApache Struts 2 Advance
Apache Struts 2 Advance
 
Wicket Security Presentation
Wicket Security PresentationWicket Security Presentation
Wicket Security Presentation
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sql
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
Polyglot parallelism
Polyglot parallelismPolyglot parallelism
Polyglot parallelism
 
Intro to Parse
Intro to ParseIntro to Parse
Intro to Parse
 

Ähnlich wie Android - Saving data

Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android Aakash Ugale
 
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.pdfAbdullahMunir32
 
12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptxFaezNasir
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 StorageDiego Grancini
 
"Android" mobilių programėlių kūrimo įvadas #3
"Android" mobilių programėlių kūrimo įvadas #3"Android" mobilių programėlių kūrimo įvadas #3
"Android" mobilių programėlių kūrimo įvadas #3Tadas Jurelevičius
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving DataAnuchit Chalothorn
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WPNguyen Tuan
 
Techniques for Cross Platform .NET Development
Techniques for Cross Platform .NET DevelopmentTechniques for Cross Platform .NET Development
Techniques for Cross Platform .NET DevelopmentJeremy Hutchinson
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4than sare
 
Ian 2014.10.24 weekly report
Ian 2014.10.24 weekly reportIan 2014.10.24 weekly report
Ian 2014.10.24 weekly reportLearningTech
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud Ouf
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorageKrazy Koder
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applicationsjeromevdl
 

Ähnlich wie Android - Saving data (20)

Android-data storage in android-chapter21
Android-data storage in android-chapter21Android-data storage in android-chapter21
Android-data storage in android-chapter21
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
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
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
 
12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 Storage
 
"Android" mobilių programėlių kūrimo įvadas #3
"Android" mobilių programėlių kūrimo įvadas #3"Android" mobilių programėlių kūrimo įvadas #3
"Android" mobilių programėlių kūrimo įvadas #3
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
 
Data management
Data managementData management
Data management
 
Data management
Data managementData management
Data management
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
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
 
Techniques for Cross Platform .NET Development
Techniques for Cross Platform .NET DevelopmentTechniques for Cross Platform .NET Development
Techniques for Cross Platform .NET Development
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
Ian 2014.10.24 weekly report
Ian 2014.10.24 weekly reportIan 2014.10.24 weekly report
Ian 2014.10.24 weekly report
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
 

Mehr von Matteo Bonifazi

Invading the home screen
Invading the home screenInvading the home screen
Invading the home screenMatteo Bonifazi
 
Engage user with actions
Engage user with actionsEngage user with actions
Engage user with actionsMatteo Bonifazi
 
Kotlin killed Java stars
Kotlin killed Java starsKotlin killed Java stars
Kotlin killed Java starsMatteo Bonifazi
 
Firebase-ized your mobile app
Firebase-ized  your mobile appFirebase-ized  your mobile app
Firebase-ized your mobile appMatteo Bonifazi
 
Android - Displaying images
Android - Displaying imagesAndroid - Displaying images
Android - Displaying imagesMatteo Bonifazi
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operationMatteo Bonifazi
 
The Firebase tier for your mobile app - DevFest CH
The Firebase tier for your mobile app - DevFest CHThe Firebase tier for your mobile app - DevFest CH
The Firebase tier for your mobile app - DevFest CHMatteo Bonifazi
 
Engage and retain users in the android world - Droidcon Italy 2016
Engage and retain users in the android world - Droidcon Italy 2016Engage and retain users in the android world - Droidcon Italy 2016
Engage and retain users in the android world - Droidcon Italy 2016Matteo Bonifazi
 
UaMobitech - App Links and App Indexing API
UaMobitech - App Links and App Indexing APIUaMobitech - App Links and App Indexing API
UaMobitech - App Links and App Indexing APIMatteo Bonifazi
 
The unconventional devices for the Android video streaming
The unconventional devices for the Android video streamingThe unconventional devices for the Android video streaming
The unconventional devices for the Android video streamingMatteo Bonifazi
 
Google IO - Five months later
Google IO - Five months laterGoogle IO - Five months later
Google IO - Five months laterMatteo Bonifazi
 
Video Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devicesVideo Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devicesMatteo Bonifazi
 

Mehr von Matteo Bonifazi (16)

Invading the home screen
Invading the home screenInvading the home screen
Invading the home screen
 
Engage user with actions
Engage user with actionsEngage user with actions
Engage user with actions
 
Kotlin killed Java stars
Kotlin killed Java starsKotlin killed Java stars
Kotlin killed Java stars
 
Android JET Navigation
Android JET NavigationAndroid JET Navigation
Android JET Navigation
 
Firebase-ized your mobile app
Firebase-ized  your mobile appFirebase-ized  your mobile app
Firebase-ized your mobile app
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
Android - Displaying images
Android - Displaying imagesAndroid - Displaying images
Android - Displaying images
 
Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operation
 
Android things intro
Android things introAndroid things intro
Android things intro
 
The Firebase tier for your mobile app - DevFest CH
The Firebase tier for your mobile app - DevFest CHThe Firebase tier for your mobile app - DevFest CH
The Firebase tier for your mobile app - DevFest CH
 
Engage and retain users in the android world - Droidcon Italy 2016
Engage and retain users in the android world - Droidcon Italy 2016Engage and retain users in the android world - Droidcon Italy 2016
Engage and retain users in the android world - Droidcon Italy 2016
 
UaMobitech - App Links and App Indexing API
UaMobitech - App Links and App Indexing APIUaMobitech - App Links and App Indexing API
UaMobitech - App Links and App Indexing API
 
The unconventional devices for the Android video streaming
The unconventional devices for the Android video streamingThe unconventional devices for the Android video streaming
The unconventional devices for the Android video streaming
 
Google IO - Five months later
Google IO - Five months laterGoogle IO - Five months later
Google IO - Five months later
 
Video Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devicesVideo Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devices
 
Enlarge your screen
Enlarge your screenEnlarge your screen
Enlarge your screen
 

Kürzlich hochgeladen

Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书rnrncn29
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleanscorenetworkseo
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Intellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxIntellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxBipin Adhikari
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxeditsforyah
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 

Kürzlich hochgeladen (20)

Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleans
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
Intellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxIntellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptx
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptx
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 

Android - Saving data

  • 1. Saving Data How to save your application data in your device +RobertoOrgiu @_tiwiz +MatteoBonifazi @mbonifazi
  • 2. Storage options Android provides several options for you to save persistent application data.
  • 4. With relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs
  • 5. Handle to a SharedPreferences Context context = getActivity(); SharedPreferences sharedPref = context.getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE); SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); getSharedPreferences() multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app. getPreferences() use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name.
  • 6. Write to Shared Preferences SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(R.string.saved_high_score), newHighScore); editor.commit();
  • 7. Read from Shared Preferences SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); int defaultValue = getResources().getInteger(R.string.saved_high_score_default); long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
  • 9. Internal or External Storage All Android devices have two file storage areas: "internal" and "external" storage. Some devices divide the permanent storage space into "internal" and "external" partitions, so even without a removable storage medium
  • 10. Internal Storage Internal storage is best when you want to be sure that neither the user nor other apps can access your files. ● It's always available. ● Files saved here are accessible by only your app. ● When the user uninstalls your app, the system removes all your app's files from internal storage.
  • 11. Create a file in Local Storage File file = new File(context.getFilesDir(), "myfile"); String string = "Hello world!"; FileOutputStream outputStream; try { outputStream = openFileOutput("myfile", Context.MODE_PRIVATE); outputStream.write(string.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); }
  • 12. External Storage The best place for files that don't require access restrictions ● It's not always available. ● It's world-readable. ● When the user uninstalls your app, the system removes your app's files from here only if you save them in the directory from getExternalFilesDir().
  • 13. Permission and Check Availability <manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> </manifest> public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; }
  • 14. Saving Data in SQL Databases
  • 15. SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC, e.t.c
  • 16. The Contract class public final class FeedReaderContract { // To prevent someone from accidentally instantiating the contract class, // make the constructor private. private FeedReaderContract() {} /* Inner class that defines the table contents */ public static class FeedEntry implements BaseColumns { public static final String TABLE_NAME = "entry"; public static final String COLUMN_NAME_TITLE = "title"; public static final String COLUMN_NAME_SUBTITLE = "subtitle"; } } A contract class is a container for constants that define names for URIs, tables, and columns. The contract class allows you to use the same constants across all the other classes in the same package.
  • 17. The Contract class private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" + FeedEntry._ID + " INTEGER PRIMARY KEY," + FeedEntry.COLUMN_NAME_TITLE + " TEXT," + FeedEntry.COLUMN_NAME_SUBTITLE + " TEXT)"; private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
  • 18. SQLiteOpenHelper public class FeedReaderDbHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "FeedReader.db"; public FeedReaderDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES);} public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); } …. } A useful set of APIs is available in the SQLiteOpenHelper class. When you use this class to obtain references to your database
  • 19. Put Information into a Database // Gets the data repository in write mode SQLiteDatabase db = mDbHelper.getWritableDatabase(); // Create a new map of values, where column names are the keys ContentValues values = new ContentValues(); values.put(FeedEntry.COLUMN_NAME_TITLE, title); values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle); // Insert the new row, returning the primary key value of the new row long newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);
  • 20. Read Information from a Database ( 1 / 2 ) SQLiteDatabase db = mDbHelper.getReadableDatabase(); // Define a projection that specifies which columns from the database String[] projection = { FeedEntry._ID, FeedEntry.COLUMN_NAME_TITLE, FeedEntry.COLUMN_NAME_SUBTITLE }; String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?"; String[] selectionArgs = { "My Title" }; // Filter results WHERE "title" = 'My Title' String sortOrder = FeedEntry.COLUMN_NAME_SUBTITLE + " DESC"; Cursor cursor = db.query/ FeedEntry.TABLE_NAME, // The table to query projection, // The columns to return selection, // The columns for the WHERE clause selectionArgs, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups sortOrder ); // The sort order
  • 21. Read Information from a Database ( 2 / 2 ) List itemIds = new ArrayList<>(); while(cursor.moveToNext()) { long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(FeedEntry._ID)); itemIds.add(itemId); } cursor.close();
  • 22. Going forward Youtube Video https://www.youtube.com/watch?v=_vQaOvPsLko https://www.youtube.com/watch?v=cp2rL3sAFmI Reference Link https://developer.android.com/training/basics/data-storage/shared-preferences.html https://developer.android.com/training/basics/data-storage/files.html https://developer.android.com/training/basics/data-storage/databases.html
  • 23. There is no ONE SOLUTION! But there are many other ways
  • 25. Defining objects @Entity public class Note { @Id private long id; private String text; private Date date; ...
  • 26. Obtaining a box notesBox = ((MyApplication) getApplication()).getBoxStore().boxFor(Note.class);
  • 27. Inserting notes Note note = new Note(0, noteText, comment, new Date()); notesBox.put(note); Log.d(App.TAG, "Inserted new note, ID: " + note.getId());
  • 29. Configuring the box //MyApplication.java boxStore = MyObjectBox.builder().androidContext(App.this).build();
  • 30. More features ● Relations ● Compatibility with GreenDAO ● Queries ● Custom Types