0% found this document useful (0 votes)
17 views31 pages

Data Persistance

Uploaded by

Mohd Aftab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views31 pages

Data Persistance

Uploaded by

Mohd Aftab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT III: DATA PERSISTENCE

SharedPreferences
 The SharedPreferences class allows you to save and
retrieve key / value pairs of primitive data types.
 We can use the SharedPreferences to save the
primitive data: booleans, floats, ints, longs, and
strings.
 These data will persist in the user session (even if
your application is dead).
 For an SharedPreferences object to your
application, use one of two methods:
 getSharedPreferences (String name, int mode) -
Use if you need several preferences files identified
by name that will be passed in the first parameter.
SharedPreferences
 getPreferences (int mode) - Use if you just
need a preferences file for your activity.
 To write values:

◦ Call the method edit () to get a


SharedPreferences.Editor;
◦ Add values methods such as putBoolean () and
putString ();
 Persists the new values with commit ().
◦ To read SharedPreferences values use the
methods as getBoolean () and getString ().
SharedPreferences
 Below is an example of storing and
removing data from a preference:
 Example of persistence with

SharedPrefereces.
File Handling
 A File object works well for reading or
writing large amounts of data.
 The exact location of the where your files

can be saved might vary across devices.


 To view files on a device, you can log the file

location provided by methods such


as File.getAbsolutePath(), and then browse
the device files with Android
Studio's DeviceFileExplorer.
File Handling
 All Android devices have two file storage areas:
"internal" and "external" storage.
 Early days of Android, most devices offered built-in
non-volatile memory (internal storage), plus a
removable storage medium such as a micro SD card
(external storage).
 Many devices now divide the permanent storage
space into separate "internal" and "external"
partitions.
 So even without a removable storage medium, these
two storage spaces always exist, and the API
behavior is the same regardless of whether the
external storage is removable.
File Handling
External storage
Internal storage  It's not always available,
because the user can mount
 It's always available. the external storage as USB
 Files saved here are storage and in some cases
accessible by only remove it from the device.
 It's world-readable, so files
your app. saved here may be read
 When the user outside of your control.
uninstalls your app,  When the user uninstalls your
app, the system removes your
the system removes app's files from here only if
all your app's files you save them in the directory
from internal from getExternalFilesDir().
storage.
File Handling
 Write a file
◦ When saving a file to internal storage, you can
acquire the appropriate directory as a File by
calling one of two methods:
 getFilesDir()
◦ Returns a File representing an internal directory
for your app.
 getCacheDir()
◦ Returns a File representing an internal directory
for your app's temporary cache files.
◦ File file = new File(context.getFilesDir(), filename);
File Handling
File Handling
 Write a cache file
◦ If you instead need to cache some files, you
should use createTempFile(). For example, the
following method extracts the file name from
a URL and creates a file with that name in your
app's internal cache directory:
File Handling
 Open an existing file
◦ To read an existing file, call openFileInput(name),
passing the name of the file.
◦ You can get an array of all your app's file names by
calling fileList().
 Open a directory
◦ You can open a directory on the internal file system
with the following methods:
 getFilesDir()
◦ Returns a File representing the directory on the file
system that's uniquely associated with your app.
File Handling
 getDir(name, mode)
◦ Creates a new directory (or opens an existing
directory) within your app's unique file system
directory. This new directory appears inside the
directory provided by getFilesDir().
 getCacheDir()
◦ Returns a File representing the cache directory on the
file system that's uniquely associated with your app.
This directory is meant for temporary files, and it
should be cleaned up regularly. The system may
delete files there if it runs low on disk space, so make
sure you check for the existence of your cache files
before reading them.
File Handling
 File directory = context.getFilesDir();
 File file = new File(directory, filename);
 Delete a file

◦ You should always delete files that your app no


longer need. The most straightforward way to
delete a file is to call delete() on the File object.
◦ myFile.delete();
External Storage
 getExternalStorageDirectory()-Root of the
External Storage
 getExternalStorageFilesDir(name,mode)-create
a dir/file for a specific application, when user
can uninstall app the files are removed.
 getExternalCacheDir()-create temporary dir-not
Accessible when SDCARD is removed
 getExternalStoragePublicDirectory()-store the
file not specific to your application,should not
removed when app is uninstalled.
How to Write
 WRITE_EXTERNAL_STORAGE –permission
 Same an internal storage

 FileOutputStream
 FileInputStream
File Handling
 Managing data using SQLite database
◦ Saving data to a database is ideal for repeating or
structured data, such as contact information.
◦ The APIs you'll need to use a database on Android
are available in
the android.database.sqlitepackage.
 Create a database using an SQL helper
◦ Once you have defined how your database looks,
you should implement methods that create and
maintain the database and tables. Here are some
typical statements that create and delete a table:
File Handling

To access your database, instantiate your


subclass of SQLiteOpenHelper
FeedReaderDbHelper mDbHelper = newFeedReaderDbHelper(getContext());
File Handling
 Put information into a database
◦ Insert data into the database by passing
a ContentValues object to the insert() method:
◦ SQLiteDatabase db=mDbHelper.getWritableDatabase();
 Read information from a database
◦ To read from a database, use the query() method,
passing it your selection criteria and desired
columns. The method combines elements
of insert() and update()
◦ SQLiteDatabase db=mDbHelper.getReadableDatabase();
File Handling
 Delete information from a database
◦ To delete rows from a table, you need to provide
selection criteria that identify the rows to
the delete() method.
File Handling
 Update a database
◦ When you need to modify a subset of your
database values, use the update() method.
 Updating the table combines
the ContentValues syntax of insert() with
the WHERE syntax of delete().
 SQLiteDatabase db=mDbHelper.getWritableDatabase();
Content providers
A Content Provider is an application
component that shares data with other
application.
Various system content providers manage
the users contacts, call logs etc.
Typically a content provider presents data as
one or more tables, similar to tables in a
database.
Content providers
 A content provider manages access to a central
repository of data.
 A provider is part of an Android application,
which often provides its own UI for working with
the data.
 A content provider presents data to external
applications as one or more tables that are
similar to the tables found in a relational
database.
 A content provider coordinates access to the
data storage layer in your application for a
number of different APIs.
Content providers
 Sharing access to your application data with
other applications
 Sending data to a widget
 Returning custom search suggestions for
your application through the search
framework
using SearchRecentSuggestionsProvider.
 Synchronizing application data with your
server using an implementation of
AbstractThreadedSyncAdapter
 Loading data in your UI using a CursorLoader
Content providers
 Accessing a provider
◦ When you want to access data in
a content provider, you use
the ContentResolver object in
your application's Context to
communicate with the provider
as a client.
◦ The ContentResolver methods
provide the basic "CRUD" (create,
retrieve, update, and delete)
functions of persistent storage.
◦ A common pattern for accessing
a ContentProvider from your UI
uses a CursorLoader to run an
asynchronous query in the
background.
Content providers
Android in build content
providers
 One of the built-in providers in the Android
platform is the user dictionary, which stores
the spellings of non-standard words that the
user wants to keep.
 Cursor c = qb.query(db, projection,
selection, selectionArgs, null,null,
sortOrder);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy