Download presentation
Presentation is loading. Please wait.
Published byMercy Cole Modified over 9 years ago
1
Android course Database dr Milan Vidaković Chair of Informatics Faculty of Technical Sciences University of Novi Sad
2
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
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
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
5/24 SQLite SQLiteDatabase class: SQLiteDatabase db = dbHelper.getWritableDatabase(); SQLiteOpenHelper class: t o open, close, create and modify database DatabaseExamples
6
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
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); } @Override public void onCreate(SQLiteDatabase _db) { _db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) { _db.execSQL("DROP TABLE IF EXISTS " + NotesDbManager.DATABASE_TABLE); onCreate(_db); }
8
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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/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);
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.