Single Application Persistent Data Storage.  Files  SharedPreferences  SQLite database.

Slides:



Advertisements
Similar presentations
Programming with Android: Data management
Advertisements

SQLite is a software library. It is: self-contained + Serverless + zero-configuration transactional = SQL database engine. Most widely deployed. The source.
 data/data-storage.html#pref data/data-storage.html#pref 
ContentProviders.  Databases for reading & writing data  Support typical database operations  e.g., query, insert, update & delete.
Cosc 5/4730 Android and Blackberry SQLite. For the sql language syntax, please see SQlite documentation –
SQLLite and Java CS-328 Dick Steflik. SQLLite Embedded RDBMS ACID Compliant Size – about 257 Kbytes Not a client/server architecture –Accessed via function.
CS378 - Mobile Computing Persistence - SQLite. Databases RDBMS – relational data base management system Relational databases introduced by E. F. Codd.
Data Persistence in Android
Data Storage: Part 1 (Preferences)
SQLite Database. SQLite Public domain database – Advantages Small (about 150 KB) – Used on devices with limited resources Each database contained within.
Data Storage: Part 3 (SQLite)
CSE 486/586, Spring 2013 CSE 486/586 Distributed Systems Content Providers & Services.
Content providers Accessing shared data in a uniform way 1Content providers.
Data Storage: Part 4 (Content Providers). Content Providers Content providers allow the sharing of data between applications. Inter-process communication.
COMP 365 Android Development.  Manages access from a central database  Allows multiple applications to access the same data.
Package org.androidtown.database.query; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
CS378 - Mobile Computing Persistence. Saving State We have already seen saving app state into a Bundle on orientation changes or when an app is killed.
Data Storage: Part 2 (File System). Internal Storage versus External Storage Internal storage − for private data –By default, files saved to the internal.
CSE 486/586, Spring 2012 CSE 486/586 Distributed Systems Recitation.
SQLite Android Club SQLite About onCreate Insert Select Update Delete onUpdate.
Android Storage. There are several options for storage of data with Android We can put data into a preferences file. We can put data into a ‘normal’ file.
Nilesh Singh Local Data Storage option Android provides several options for you to save persistent application data. - Shared preferences - Creation.
Data persistence How to save data using SharedPreferences, Files, and SQLite database 1Data persistence.
Address Book App 1. Define styles   Specify a background for a TextView – res/drawable/textview_border.xml.
9 Persistence - SQLite CSNB544 Mobile Application Development Thanks to Utexas Austin.
Data Persistence Nasrullah Niazi. Share Preferences The SharedPreferences class provides a general framework that allows you to save and retrieve persistent.
CS378 - Mobile Computing Persistence. Saving State We have already seen saving app state into a Bundle on orientation changes or when an app is killed.
Persistence Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.
Mobile Software Development ISCG 7424 Department of Computing UNITEC John Casey and Richard Rabeder SQLite and Permissions.
SQLite DB Storing Data in Android RAVI GAURAV PANDEY 1.
Android: “Dynamic” data and Preferences data.
Android - SQLite Database 12/10/2015. Introduction SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with.
SQlite. 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.
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Android Boot Camp.
Address Book App 1 Fall 2014 CS7020: Game Design and Development.
CHAPTER 9 File Storage Shared Preferences SQLite.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
Data Storage in Android Димитър Н. Димитров. Why talk about data? Why not 3D graphics or network connectivity? Data as fundamental term in computer science.
Database Programming Code Dissection. Layered Approach Presentation (Activity) DbSampleActivity.java DataAccess (DataSource) CommentsDataSource.java MySQLiteHelper.java.
Data Persistence Chapter 9. Objectives Learn about data storage methods Understand use of Shared Preferences Understand file-based storage and the differences.
CS499 – Mobile Application Development
Making content providers
Data Storage: Part 3 (SQLite)
Data Storage: Part 4 (Content Providers)
Data Storage: Part 2 (File System)
CS371m - Mobile Computing Persistence.
Android Application Data Storage 1.
SQLite in Android Landon Cox March 2, 2017.
Mobile Software Development for Android - I397
Mobile Application Development BSCS-7 Lecture # 18, 19
Android Application SQLite 1.
Reactive Android Development
Android Database using SQLite
Android 4: Saving Data Kirk Scott.
Mobile Application Development Chapter 5 [Persistent Data in Android]
Android 18: Saving Data Kirk Scott.
I/O Basics.
Mobile Computing With Android ACST 4550 Android Data Storage
Android Storage.
Mobile Computing With Android ACST Android Database Storage Part 2
Android Programming Lecture 7
CMPE419 Mobile Application Development
Mobile Computing With Android ACST 4550 Android Database Storage
Android Developer Fundamentals V2
Web Design & Development Lecture 8
ListView A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view. ListAdapter is used to.
Department of School of Computing and Engineering
SQLLite and Android.
Mobile Programming Dr. Mohsin Ali Memon.
Preference Activity class
Presentation transcript:

Single Application Persistent Data Storage

 Files  SharedPreferences  SQLite database

 Represents a file system entity identified by a pathname  Storage areas classified as internal or external  Internal memory usually used for application private files  External memory used for public files

 boolean isDirectory()  Return true if this File represents a directory  String getAbsolutePath()  Returns the absolute path to this File  boolean setReadable(boolean readable)  Sets read permission on this File  Many others. See documentation.

// Open file. Get FileOutputStream FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE); PrintWriter pw = new PrintWriter( new BufferedWriter(new OutputStreamWriter(fos))); // Write to file pw.println(…); … // Close file pw.close();

// Open file. Get FileInputStream FileInputStream fis = openFileInput(fileName); BufferedReader fr = new BufferedReader(new InputStreamReader(fis)); String line = ""; // Read from file while (null != (line = fr.readLine())) { // process data } // Close file br.close();

 Cache files are temporary files that may be deleted by the system when storage is low  File Context.getCacheDir()  Returns absolute path to an application-specific directory that can be used for temporary files  Files removed when application uninstalled

 Removable media may appear/disappear without warning  String Environment.getExternalStorageState()  MEDIA_MOUNTED - present & mounted with read/write access  MEDIA_MOUNTED_READ_ONLY - present & mounted with read-only access  MEDIA_REMOVED - not present  Need permission to write external files 

public class FileWriteAndReadActivity extends Activity { public void onCreate(Bundle savedInstanceState) { … if (Environment.MEDIA_MOUNTED.equals( Environment.getExternalStorageState())) { File outFile = new File(getExternalFilesDir( Environment.DIRECTORY_PICTURES),fileName); try { BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(outFile)); BufferedInputStream is = new BufferedInputStream(getResources().openRawResource(R.drawable.icon)); copy(is, os); } catch (FileNotFoundException e) {} } …

private void copy(InputStream is, OutputStream os) { final byte[] buf = new byte[1024]; int numBytes; try { while (-1 != (numBytes = is.read(buf))) { os.write(buf, 0, numBytes); } } catch (IOException e) {… } finally { try { is.close(); os.close(); } catch (IOException e) {} …

 Context.getExternalCacheDir() returns a File representing external storage directory for cache files  Files removed when application uninstalled

 A persistent map  Holds key-value pairs of primitive data types  Automatically managed across application uses  Often used for long-term storage of customizable application data such as user preferences, e.g.,  User ID  Favorite Wifi networks

 Activity.getPreferences (int mode)  Mode: MODE_PRIVATE, MODE_WORLD_READABLE or MODE_WORLD_WRITEABLE  Returns a SharedPreference object for the current Activity

 Context.getSharedPreferences ( String name, int mode)  name – name of SharedPreference file  mode – MODE_PRIVATE, MODE_WORLD_READABLE or MODE_WORLD_WRITEABLE  Returns named SharedPreference object for this context

 Call SharedPreferences.edit()  Returns a SharedPreferences.Editor instance  Add values with SharedPreferences.Editor  Commit values with SharedPreferences.Editor.commit()

 Use SharedPreferences methods, e.g.,  getAll()  getBoolean()  getString()

public class SharedPreferenceReadWriteActivity extends Activity { private static String HIGH_SCORE = "high_score"; public void onCreate(Bundle savedInstanceState) { … final SharedPreferences prefs = getPreferences(MODE_PRIVATE); final Button go = … go.setOnClickListener(new OnClickListener() { public void onClick(View v) { … int val= … if (val > prefs.getInt(HIGH_SCORE, 0)) { … SharedPreferences.Editor editor = prefs.edit(); editor.putInt(HIGH_SCORE, val); editor.commit(); } …

 Class that supports displaying & modifying user preferences

public class DataManagementPreferencesActivity extends Activity { SharedPreferences prefs; final static String USERNAME = "uname"; public void onCreate(Bundle savedInstanceState) { … prefs = PreferenceManager. getDefaultSharedPreferences(getApplicationContext()); final Button button = …; button.setOnClickListener(new OnClickListener() { public void onClick(View v) { startActivity(new Intent (DataManagementPreferencesActivity.this, LoadPreferencesActivity.class)); } }); } …

public class LoadPreferencesActivity extends PreferenceActivity { protected void onCreate(Bundle savedInstanceState) { … final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); addPreferencesFromResource(R.xml.user_prefs); final EditTextPreference uNamePref = (EditTextPreference) getPreferenceScreen().findPreference(USERNAME); uNamePref.setSummary(prefs.getString(USERNAME, "")); prefs.registerOnSharedPreferenceChangeListener( new OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { uNamePref.setSummary(prefs.getString(USERNAME, "")); } }); …

<EditTextPreference android:negativeButtonText="Cancel" android:dialogMessage="Enter Your User Name" android:dialogTitle="User Name" android:positiveButtonText="Submit" android:title="User Name" android:key="uname">

 SQLite provides in-memory database  Designed to operate within a very small footprint (<300kB) within a single cross- platform disk file  Implements most of SQL92  Supports ACID transactions  Atomic, consistent, isolated & durable

 Recommended method relies on a helper class called SQLiteOpenHelper  Create a subclass SQLOpenHelper  Override onCreate()  Execute CREATE TABLE command  Use Constructor to instantiate subclass  Use SQLiteOpenHelper methods to open & return underlying database

public class DatabaseOpenHelper extends SQLiteOpenHelper { final private static String CREATE_CMD = "CREATE TABLE artists (” + “_id”+ “ INTEGER PRIMARY KEY AUTOINCREMENT, ” + “name” + " TEXT NOT NULL)”; public DatabaseOpenHelper(Context context) { super(context, “artist_db”, null, 1); } public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_CMD); } …

public class DatabaseExampleActivity extends ListActivity { final static String[] columns ={ _ID, ARTIST_NAME }; static SQLiteDatabase db = null; public void onCreate(Bundle savedInstanceState) { … DatabaseOpenHelper dbHelper = new DatabaseOpenHelper(this); db = dbHelper.getWritableDatabase(); insertArtists(); Cursor c = readArtists(); deleteLadyGaga(); setListAdapter(new SimpleCursorAdapter( this, R.layout.list_layout, c, new String { _ID, ARTIST_NAME }, new int[] { R.id._id, R.id.name })); }

private void insertArtists() { ContentValues values = new ContentValues(); values.put(ARTIST_NAME, "Lady Gaga"); db.insert(TABLE_NAME, null, values); values.clear(); values.put(ARTIST_NAME, "Johnny Cash"); db.insert(TABLE_NAME, null, values); values.clear(); values.put(ARTIST_NAME, "Ludwig von Beethoven"); db.insert(TABLE_NAME, null, values); }

private int deleteLadyGaga() { return db.delete( TABLE_NAME, ARTIST_NAME+"=?", new String [] {"Lady Gaga"}); }

private Cursor readArtists() { // returns all rows return db.query( TABLE_NAME, new String [] {“_id”,”name”} null, new String[] {}, null, null, null); }

… Cursor c = readArtists(); setListAdapter( new SimpleCursorAdapter( this, R.layout.list_layout, c, new String [] {“_id”, “name”}, new int[] { R.id._id, R.id.name })); …

 Databases stored in  /data/data/ /databases/  Can examine database with sqlite3  # adb -s emulator-5554 shell  # sqlite3 /data/data/course.examples. DataManagement.DataBaseExample/ databases/artist_db