Persistence Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.

Slides:



Advertisements
Similar presentations
Programming with Android: Data management
Advertisements

ContentProviders.  Databases for reading & writing data  Support typical database operations  e.g., query, insert, update & delete.
Cosc 5/4730 Android Content Providers and Intents.
컨텐트 프로바이더 박승제. Content Provider The only way to share data across applications Using content provider Use existing content providers supplied by android.
CONTENT PROVIDER. Content Provider  A content provider makes a specific set of the application's data available to other applications => Share data to.
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.
CSE 486/586, Spring 2013 CSE 486/586 Distributed Systems Content Providers & Services.
Cosc 5/4730 Android Content Providers and Intents.
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.
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.
CSE 486/586, Spring 2012 CSE 486/586 Distributed Systems Recitation.
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.
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.
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.
SQLite (part deux) 1 CS440. Traditional Model View Controller (MVC) CS440 2.
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 Application Lifecycle and Menus
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.
1. Playing with SQLite Database  SQLite : Database specific name for Android Application  For windows there are several kind of database name : Mysql,
Address Book App 1 Fall 2014 CS7020: Game Design and Development.
CHAPTER 9 File Storage Shared Preferences SQLite.
Intents and Broadcast Receivers Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution.
Android Storage MAY 2013 Hu.Cai. NAME OF PRESENTATION [CHANGE IN SLIDE MASTER] MONTH, YEAR [CHANGE IN SLIDE MASTER] Outline 1.Storage In General 2.SharedPreferences.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
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.
CS371m - Mobile Computing Persistence - SQLite. 2 In case you have not taken 347: Data Management or worked with databases as part of a job, internship,
Content Providers.
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)
Content provider.
Cosc 5/4730 Sqlite primer.
Android Content Providers & SQLite
Data Storage: Part 4 (Content Providers)
Content Providers And Content Resolvers
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
CS499 – Mobile Application Development
Mobile Application Development Chapter 5 [Persistent Data in Android]
Content Providers.
Android Storage.
Mobile Computing With Android ACST Android Database Storage Part 2
Android Programming Lecture 7
CMPE419 Mobile Application Development
CS371m - Mobile Computing Persistence - SQLite.
CMPE419 Mobile Application Development
Mobile Computing With Android ACST 4550 Android Database Storage
lec 05 Admin stuff; schedule IOS versus Android Preferences
Android Developer Fundamentals V2
Department of School of Computing and Engineering
SQLLite and Android.
plus content providers, loaders, recyclerview
Mobile Programming Dr. Mohsin Ali Memon.
Presentation transcript:

Persistence Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.

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

Shared Preferences Three forms: –Share across all components in an application getSharedPreferences(“SomeString”,Activity.MODE_PRIVATE); –Store only data needed by this Activity 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

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); }

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); }

Shared Preferences Only for this Activity when inactive/active –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)); }

Files Generally not recommended to use files Store read-only static files in res/raw InputStream myFile = getResources().openRawResource(R.raw.myfilename);

Files Standard java.io is available Can also use openFileOutput and openFileInput byte[] b = new String("Yo").getBytes(); try { FileOutputStream fos = openFileOutput("anotherExampleFile.txt", Context.MODE_WORLD_WRITEABLE); fos.write(b); FileInputStream fis = openFileInput("anotherExampleFile.txt"); fis.read(b); } catch (IOException e) {} Also available: Context.MODE_PRIVATE Context.MODE_WORLD_READABLE

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 –Normalize data –Encapsulate db info in helper or wrapper classes Don’t store files (e.g. images or audio) –Instead store the path string

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);");

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);

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

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()); }

Other Cursor Functions moveToPrevious getCount getColumnIndexOrThrow getColumnName getColumnNames moveToPosition getPosition

Deleting Data myDb.delete("jokeTable", "author='David Janzen'", null);

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

Content Resolver Each application Context has a single ContentResolver that can be used to access a Content Provider 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()); } URI,colums,where,whereArgs,orderBy Requires:

Insert, Update, Delete Similar to SQLiteDatabase Update and Delete are similar 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(); 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);

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 = 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); }

Provide query, insert, delete, 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; }

getType() and manifest In public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case SINGLE_ROW : return “vnd.simexusa.cursor.item/mapprovider”; case ALLROWS : return “vnd.simexusa.cursor.dir/mapprovider”; default: : throw new IllegalArgumentException(“Unsupported URI: “ + uri); } <provider android:name=“MapProvider” android:authorities=“com.simexusa.provider.campusmap” />