Cosc 5/4730 Android Content Providers and Intents.

Slides:



Advertisements
Similar presentations
Programming with Android: Data management
Advertisements

Bruce Scharlau, University of Aberdeen, 2012 Data storage options for mobiles Mobile Computing.
 data/data-storage.html#pref data/data-storage.html#pref 
ListView Examples. Basic Steps for Creating a Listview 1.Create a layout (e.g., a LinearLayout), with elements for –the ListView (
Android – CoNTENT PRoViders
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.
Cosc 5/4730 Android SMS. A note first Depending on the API level, an import changes because of a deprecated API 3 uses – import android.telephony.gsm.SmsManager;
CONTENT PROVIDER. Content Provider  A content provider makes a specific set of the application's data available to other applications => Share data to.
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.
Introducing the Sudoku Example
CSE 486/586, Spring 2013 CSE 486/586 Distributed Systems Content Providers & Services.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
ContentProviders. SQLite Database SQLite is a software library that implements aself- contained, serverless,zero- configuration,transactionalSQL database.
ANDROID CONTENT PROVIDERS Peter Liu School of ICT, Seneca College.
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.
Rajab Davudov. Agenda Eclipse, ADT and Android SDK APK file Fundamentals – Activity – Service – Content Provider – Broadcast Receiver – Intent Hello World.
DUE Hello World on the Android Platform.
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 Content Providers In Android security model, one application cannot directly access (read/write) other application's data. Every application has.
CS378 - Mobile Computing Intents. Allow us to use applications and components that are part of Android System – start activities – start services – deliver.
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.
9 Persistence - SQLite CSNB544 Mobile Application Development Thanks to Utexas Austin.
© 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.
Cosc 5/4730 Android Communications Intents, callbacks, and setters.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
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.
Working with Multiple Activities. Slide 2 Introduction Working with multiple activities Creating multiple views Introduction to intents Passing data to.
SQLite DB Storing Data in Android RAVI GAURAV PANDEY 1.
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.
CSE 486/586, Spring 2014 CSE 486/586 Distributed Systems Android Programming Steve Ko Computer Sciences and Engineering University at Buffalo.
© 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.
David Sutton USING CONTENT PROVIDERS. TOPICS COVERED THIS WEEK  Persistence  Introduction to databases  Content providers  Cursors  Cursor adapters.
CHAPTER 9 File Storage Shared Preferences SQLite.
This was written with the assumption that workbooks would be added. Even if these are not introduced until later, the same basic ideas apply Hopefully.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
The Ingredients of Android Applications. A simple application in a process In a classical programming environment, the OS would load the program code.
Working with Multiple Activities. Slide 2 Introduction Working with multiple activities Putting together the AndroidManifest.xml file Creating multiple.
Data Storage in Android Димитър Н. Димитров. Why talk about data? Why not 3D graphics or network connectivity? Data as fundamental term in computer science.
Content Providers.
Cosc 4735 Nougat API 24+ additions.
Making content providers
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.
Android Application SQLite 1.
CS499 – Mobile Application Development
Mobile Application Development Chapter 5 [Persistent Data in Android]
Content Providers.
Android Notifications (Part 2) Plus Alarms and BroadcastReceivers
Mobile Computing With Android ACST 4550 Android Database Storage
Android Developer Fundamentals V2
plus content providers, loaders, recyclerview
Mobile Programming Dr. Mohsin Ali Memon.
Preference Activity class
Presentation transcript:

Cosc 5/4730 Android Content Providers and Intents

Data storage There are several methods to store data – Preferences is a lightweight mechanism to store and retrieve key-value pairs of primitive data types. It is typically used to store application preferences – Files System – Databases Content Providers – These use one of the above or something else (say networking) – Only method to "share" information between applications.

Content Providers Any Uri that begins with content:// is retrieved with a content provider. – The data is encapsulated using a Uri instance – You don't know where it is, nor care actually – Could be a database, files, or retrieved from off the device With a Uri, you perform basic CRUD operations using the content provider – CRUD = create, read, update, delete

URI Examples: content://media/internal/images – return the list of all internal images on the device. content://contacts/people/ – return the list of all contact names on the device. – Better to use the build in ContactsContract.Contacts.CONTENT_URI content://contacts/people/45 – return the single result row, the contact with ID=45. content://mms – returns a list of the mms messages (content://mms/part/ gets the message) content://constants/5 – return the constant number 5 content://edu.cs4730.provider/square – a custom content provider covered later in the lecture.

URI (2) android.providers package provide some ready made URIs, example: – ContactsContract.Contacts.CONTENT_URI – MediaStore.Images.Media.INTERNAL_CONTENT_ URI Otherwise, use Uri.parse(String); Uri CONTENT_URI = Uri.parse("content://"+ PROVIDER_NAME + "/square"); Uri CONTENT_URI = Uri.parse("content://"+ PROVIDER_NAME + "/cube/1");

Android Content Providers Android provides an example of how to use the built-in user dictionary. – ers/content-provider-basics.html ers/content-provider-basics.html They is also a description of Contacts and Calendar Providers – ers/contacts-provider.html ers/contacts-provider.html – ers/calendar-provider.html ers/calendar-provider.html

Contacts Example Simple code to read the contacts Note, need at least these permissions – Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI; String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; Cursor c = managedQuery(CONTENT_URI, projection, null, null, null); if (c.moveToFirst()) { do { String str = "Id: " + c.getString(0); str += "Name: " + c.getString(1); } while (c.moveToNext()); } The ContentProvider Demo has a better version of this showing the contacts in a listview. Note, if running on the emulator, you will to create some contacts to display!

Custom Content Providers Content Providers share content with applications across application boundaries. This allows us to make information/data available between applications (including ones we write) – This provides a way to hide how we are storing the data and present to our activity in a standard way as well. – The query method returns a Cursor So we will have take our data and put it in a cursor (assuming it not a database, which already returns cursors).

Custom Content Providers (2) Note to remember – There is a provider name As example: edu.cs4730.provider – There is a data section As example: edu.cs4730.provider/cube – Provides cube information As example: edu.cs4730.provider/square – Provides square information – There is a “row” section of the any data section as well As example: edu.cs4730.provider/square/2 – If exists, provides row 2 of the square section of data.

Custom Content Providers (2) Extend the ContentProvider class and implement the required methods. – getType(): Returns the MIME type of the data at the given URI. – onCreate(): Called when the provider is being started. – query(): Receives a request from a client. The result is returned as a Cursor object. – insert(): Inserts a new record into the content provider. – delete(): Deletes an existing record from the content provider. – update(): Updates an existing record from the content provider.

Custom Content Providers (3) With our content provider we can choose how to store the data: – file system, xml, database, or on the internet For this lecture example: – A dummy content provider – It ignore inserts, updates, deletes – It will return the cube or square of the number sent to it, depends on the data section queried. Zero for non numbers Square/cube for 1 to 10 for “all rows” query

Creating a Custom Content Provider create a class that extends ContentProvider – In studio, if you says new -> Content provider It will as for the provider name in the setup – Create the entry in the Androidmanifest.xml file correctly. And give you all the methods that need to be overridden. – In our case: public class dummyCP extends ContentProvider { – Most of the methods are going to leave with the default return value (null or 0)

Creating a Custom Content Provider (2) Remember, – A content provider is basically just a wrapper to the data model you have already created. – So for this example There is a cube.java and square.java class that already exists to provide the data for the queries.

Constants we need public static final String PROVIDER_NAME = "edu.cs4730.provider"; public static final Uri CONTENT_URI1 = Uri.parse("content://"+ PROVIDER_NAME + "/square"); public static final Uri CONTENT_URI2 = Uri.parse("content://"+ PROVIDER_NAME + "/cube"); These are the ContentProvider information to access it later.

UriMatcher private static final int SQUARE = 1; private static final int SQUARE_ID = 2; private static final int CUBE = 3; private static final int CUBE_ID = 4; private static final UriMatcher uriMatcher; static{ uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, "sqaure", SQUARE); uriMatcher.addURI(PROVIDER_NAME, "square/#", SQUARE_ID); uriMatcher.addURI(PROVIDER_NAME, "cube", CUBE); uriMatcher.addURI(PROVIDER_NAME, "cube/#", CUBE_ID); } Observe from the code above that you use a UriMatcher object to parse the content URI that is passed to the content provider through a Content Resolver. For example, the following content URI represents a request for all rows in the content provider: content://edu.cs4730.provider/square In contrast, the following represents a request for a particular row with _id=5: content://edu.cs4730.provider/square/5

override getType() You'll need to override the getType() method so it uniquely describes the data type for your content provider. – Using the UriMatcher object, you will return "vnd.android.cursor.item/vnd.cs4730.square" for a single row, and "vnd.android.cursor.dir/vnd.cs4730.square" for multiple public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case SQUARE: // get all rows of square return "vnd.android.cursor.dir/vnd.cs4730.square"; case SQUARE_ID: //get a one row of square return "vnd.android.cursor.item/vnd.cs4730.square"; case CUBE: // get all rows for cube return "vnd.android.cursor.dir/vnd.cs4730.cube"; case CUBE_ID: // get a particular row for cube return "vnd.android.cursor.item/vnd.cs4730.cube"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); }

Query public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String stuff; switch (uriMatcher.match(uri)) { case SQUARE_ID: //get one row from the square. stuff = uri.getPathSegments().get(1); int val = Integer.parseInt(stuff); //convert from String to int. return mySquare.getone(val); case SQUARE: //get all the rows of square return mySquare.getall(); case CUBE_ID: //same idea of square_id, uses myCube.getone(val); saving space on the slide. case CUBE: //get all the rows of cube return myCube.getall(); } Log.d(TAG, "query null..."); //something else, just return null or maybe should throw an exception? return null;}

MatrixCursor android.database.MatrixCursor – This allows us to create an editable Cursor We can’t add to a standard Cursor. – On instancesation of the Matrix Cursor, we provide it an array of strings that are the Column names. – Then use myCursor.addRow(new Object[]); Where the Object[] array is the entries for the row. In the example I just has it cast integers to the generic Object type.

MatrixCursor (2) For cube the methods look like this to create the cursor: Column = new String[] { "number", "cube"}; public Cursor getone(int val) { //must return a Cursor, MatrixCursor is an editable cursor. MatrixCursor myCursor = new MatrixCursor(Column); myCursor.addRow(new Object[] { val, val*val*val }); return myCursor; } //returns the number and number of the number from 1 to 10. public Cursor getall() { MatrixCursor myCursor = new MatrixCursor(Column); for (int i=1; i<11; i++) { myCursor.addRow(new Object[] { i, i*i*i}); } return myCursor; }

The Rest of the public boolean onCreate() { //nothing to create, so just return true return true; public Uri insert(Uri uri, ContentValues values) { //ignore insert return null; public int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) { // ignore, return default return 0; public Uri insert(Uri uri, ContentValues values) { // ignore, return default return null; public int delete(Uri uri, String selection, String[] selectionArgs) { // ignore, return default return 0; }

Register the provider In the AndroidManifest.xml file – add the class the is the provider and register the content string <activity … <provider android:name=“dummyCP" android:authorities="edu.cs4730.provider" android:enabled="true" android:exported="true"/>

Activity class Now in the activity class we can use it. example, select one of them, in this case 2 Uri onerow = Uri.parse("content://edu.cs4730.provider/square/2"); Cursor c = getContentResolver().query(onerow, null, null, null, null); if (c != null) { c.moveToFirst(); do { logThis(c.getString(0) + " value is " + c.getString(1)); } while (c.moveToNext()); } now select "all", which will return 1 to 10 cube. Uri allrow = Uri.parse("content://edu.cs4730.provider/cube"); c = getContentResolver().query(allrow, null, null, null, null);...

Loaders Loaders allow you to keep the data in the cursors update from Content Providers – We’ll come back to them in the sqlite lecture.

References content-providers.html content-providers.html base/Cursor.html base/Cursor.html base/MatrixCursor.html base/MatrixCursor.html Using and Implementing Content Providers in Android –

Q A &