Android course Database dr Milan Vidaković Chair of Informatics Faculty of Technical Sciences University of Novi Sad.

Slides:



Advertisements
Similar presentations
Programming with Android: Data management
Advertisements

SQLite. Command line sqlite3 The command line sqlite3 is not installed on all devices To install, get sqlite3 from web page, and $ adb push sqlite3 /sdcard/
CE881: Mobile and Social Application Programming Flexible Data Handling with Integrity: SQLite Simon M. Lucas.
SQLite is a software library. It is: self-contained + Serverless + zero-configuration transactional = SQL database engine. Most widely deployed. The source.
SQLite in Mobile Apps by Dan Youberg. Overview Many well known applications and Internet browsers use SQLite due to its very small size (~250 Kb). Also.
ContentProviders.  Databases for reading & writing data  Support typical database operations  e.g., query, insert, update & delete.
컨텐트 프로바이더 박승제. 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.
SQLite 1 CS440. What is SQLite?  Open Source Database embedded in Android  SQL syntax  Requires small memory at runtime (250 Kbytes)  Lightweight.
CS378 - Mobile Computing Persistence - SQLite. Databases RDBMS – relational data base management system Relational databases introduced by E. F. Codd.
Data Persistence in Android
SQLite Database. SQLite Public domain database – Advantages Small (about 150 KB) – Used on devices with limited resources Each database contained within.
Database Rung-Hung Gau Department of Computer Science and Engineering
Data Storage: Part 3 (SQLite)
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.
Package org.androidtown.database.query; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
SQLite Android Club SQLite About onCreate Insert Select Update Delete onUpdate.
SQLite Supported by BlackBerry OS 5.0 Using SQLite.
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.
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.
Copyright© Jeffrey Jongko, Ateneo de Manila University Custom ListAdapters.
Persistence Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.
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 - 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.
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
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.
CS499 – Mobile Application Development
Making content providers
Data Storage: Part 3 (SQLite)
Android aplikacija i baze podataka
Content provider.
Cosc 5/4730 Sqlite primer.
Android Content Providers & SQLite
Mobile Applications (Android Programming)
Data Storage: Part 4 (Content Providers)
Content Providers And Content Resolvers
SQLite in Android Landon Cox March 2, 2017.
Mobile Software Development for Android - I397
Mobile Application Development BSCS-7 Lecture # 18, 19
ListView: Part 2.
Android Application SQLite 1.
Reactive Android Development
CS499 – Mobile Application Development
Android Database using SQLite
Content Providers.
Mobile Computing With Android ACST Android Database Storage Part 2
CMPE419 Mobile Application Development
CS371m - Mobile Computing Persistence - SQLite.
CMPE419 Mobile Application Development
Mobile Computing With Android ACST 4550 Android Database Storage
HNDIT2417 Mobile Application Development
Android Developer Fundamentals V2
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.
Lecture 8: Database Topics: Basic SQLite Operations.
Mobile Programming Dr. Mohsin Ali Memon.
Presentation transcript:

Android course Database dr Milan Vidaković Chair of Informatics Faculty of Technical Sciences University of Novi Sad

2/24 Database What is relational database model? simplified answer: database consists of tables table is just like the one in the Excel Each table has rows and columns Each column has: name, type (int, string,...), undefined value or not (null), is it primary key or not (primary key), etc.

3/24 Primary key Primary key: a column(s) which identifies a row Student index, vehicle registration plate Primary key can be autoincrement Integer value which is incremented when a row is inserted in a table

4/24 Android database Android comes with SQLite database Features: self-contained, serverless, zero-configuration and transactional All the tables are placed in the /data folder (the only read-write folder on Android (except for the /sdcard folder content – SD card))

5/24 SQLite SQLiteDatabase class: SQLiteDatabase db = dbHelper.getWritableDatabase(); SQLiteOpenHelper class: t o open, close, create and modify database DatabaseExamples

6/24 Helper class Extends SQLiteOpenHelper class Overrides: onCreate(SQLiteDatabase) onOpen(SQLiteDatabase) onUpgrade(SQLiteDatabase, old_ver, new_ver) onDowngrade(SQLiteDatabase, old_ver, new_ver)

7/24 Helper class public class MyDbHelper extends SQLiteOpenHelper { private static final String DATABASE_CREATE = "create table NOTES ( " + " _id integer primary key autoincrement, " + " naslov text not null, " + " vreme text not null, " + " tekst text not null);"; public MyDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); public void onCreate(SQLiteDatabase _db) { _db.execSQL(DATABASE_CREATE); public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) { _db.execSQL("DROP TABLE IF EXISTS " + NotesDbManager.DATABASE_TABLE); onCreate(_db); }

8/24 SQLite database CRUD (Create, Read, Update, Delete): long insert(String table, String null_hack, ContentCalues entry) Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) int update(String table, ContentValues values, String whereClause, String[] whereArgs) int delete(String table, String whereClause, String[] whereArgs)

9/24 Insert Content to be inserted must be placed in the ContentValues map: ContentValues newEntry = new ContentValues(); newEntry.put(“FirstName”, “Pera”); newEntry.put(“LastName”, “Peric”); long id = db.insert(DATABASE_TABLE, null, newEntry); Returns Id of the insterted row Important when PK is autoincrement!

10/24 Query Return value is a cursor which is used to browse query results If criteria, group by, having, order by, and limit is omitted, lists the whole table: Cursor c = db.query(DATABASE_TABLE, new String[] { _ID, TITLE, TIMESTAMP, TEXT }, null, null, null, null, null);

11/24 Query Query: cursor = db.query(true, DATABASE_TABLE, new String[] {_ID,TITLE,TIMESTAMP,TEXT}, _ID + "=?", new String[] {id}, null, null, null, null); Raw query: cursor = db.rawQuery("select _ID, TITLE, TIMESTAMP, TEXT from DATABASE_TABLE where ID=?", new String[] {id});

12/24 Cursor To browse and read query results Browse: move(offset) moveToFirst(), moveToLast(), moveToNext(), moveToPrevious() isFirst(), isLast(), isAfterLast(), isBeforeFirst() Read: getCount() getString(column_index) getInt(column_index) getColumnIndex(“LastName”);

13/24 Update Updates column(s): ContentValues newValue = new ContentValues(); newValue.put(“FirstName”, “MIKA”); newValue.put(“LastName”, “MIKIC”); int rows = db.update(DATABASE_TABLE, newValue, _ID + "=?", new String[] {id}); SQL equivalent: update DATABASE_TABLE set FirstName=“MIKA”, LastName=“MIKIC” where _ID=id If filter criteria is omitted, it will update all rows! Last two arguments are filter criteria and its parameters Returns the number of affected rows

14/24 Delete Deletes a row: int rows = db.delete(DATABASE_TABLE, _ID + "=?", new String[] {id}); SQL equivalent: delete from DATABASE_TABLE where _ID=id If filter criteria is omitted, it will update all rows! Last two arguments are filter criteria and its parameters Returns the number of affected rows

15/24 Data read To start reading query results: startManagingCursor(cur); This method binds cursor to Activity from which it has been created If an activity is stopped, it will invoke cursor.deactivate() If an activity is restarted, it will invoke cursor.requery() If an activity is destroyed, it will close the cursor Each ListView has a ListAdapter which binds data and ListView – SimpleCursorAdapter class is used to bind query results to a ListView DatabaseExamples

16/24 SimpleCursorAdapter A kind of ListAdapter, which binds cursor to a ListView Procedure: execute query, create SimpleCursorAdapter, and put that adapter as a soruce to a ListView

17/24 SimpleCursorAdapter Constructor: ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, cur, new String[] { “FirstName”, “LastName”}, new int[] { R.id.firstname, R.id.lastname }); Second argument (R.layout.list_item) is a resource ID which will visualise a row Third argument is a cursor Fourth argument is a list of column names in a db table Fifth argument is a list of component ids bound to appropriate columns in a table Components are part of a row component (R.layout.list_item)

18/24 List multimedia files List multimeida files on a device String[] proj = { MediaStore.Video.Media._ID, MediaStore.Video.Media.DATA, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.SIZE }; mediaCursor = managedQuery(MediaStore.Video.Media.EXTERN AL_CONTENT_URI, proj, null, null, null); DatabaseExamples

19/24 List multimedia files How to bind query result and ListView? Create custom Adapter, which extends BaseAdapter class MMediaAdapter extends BaseAdapter { private Context vContext; public MMediaAdapter(Context c) { vContext = c; } public int getCount() { return mediaCursor.getCount(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; }

20/24 List multimedia files public View getView(int position, View oldView, ViewGroup parent) { System.gc(); TextView tv; String id = null; if (oldView == null) { tv = new TextView(vContext.getApplicationContext()); int media_column_index = mediaCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME); mediaCursor.moveToPosition(position); id = mediaCursor.getString(media_column_index); media_column_index = mediaCursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE); mediaCursor.moveToPosition(position); id += " Size(KB):" + mediaCursor.getString(media_column_index); tv.setText(id); } else tv = (TextView) oldView; return tv; }

21/24 Browse bookmarks and web history Android browsers record all bookmarks and history in a database Table has an alias: android.provider.Browser.BOOKMARKS_URI Columns: Browser.BookmarkColumns.TITLE Browser.BookmarkColumns.URL Browser.BookmarkColumns.CREATED Browser.BookmarkColumns.BOOKMARK – 1 for a bookmark; 0 for history DatabaseExamples

22/24 Browse bookmarks and web history String[] columns = new String[] { Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL, Browser.BookmarkColumns.CREATED }; Cursor cur = managedQuery(android.provider.Browser.BOOKMARKS_URI, columns, null, null, null); ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.bookmark_item, cur, new String[] { Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL, Browser.BookmarkColumns.CREATED}, new int[] { R.id.bookmark_title, R.id.bookmark_url, R.id.bookmark_created }); ListView mainList = (ListView) findViewById(R.id.bookmarks_list); mainList.setAdapter(adapter);

23/24 Call history Android records all voice calls history in a database Table alias: CallLog.Calls.CONTENT_URI Columns: Calls.NUMBER Calls.CACHED_NAME Calls.DURATION Calls.DATE Calls.TYPE (incoming, outgoing, missed) DatabaseExamples

24/24 Call history String[] columns = new String[] {Calls._ID, Calls.NUMBER, Calls.CACHED_NAME, Calls.DURATION }; Cursor cur = managedQuery(CallLog.Calls.CONTENT_URI, columns, null, null, null); ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.call_history_item, cur, new String[] { Calls.NUMBER, Calls.CACHED_NAME, Calls.DURATION}, new int[] { R.id.call_number, R.id.call_name, R.id.call_duration }); ListView mainList = (ListView)findViewById(R.id.call_history_list); mainList.setAdapter(adapter);