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/

Slides:



Advertisements
Similar presentations
PHP: Date() Function The PHP date() function formats a timestamp to a more readable date and time.
Advertisements

Android Application Development Tutorial. Topics Lecture 4 Overview Overview of Sensors Programming Tutorial 1: Tracking location with GPS and Google.
Programming with Android: Data management
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
CE881: Mobile and Social Application Programming Flexible Data Handling with Integrity: SQLite Simon M. Lucas.
Quick-and-dirty.  Commands end in a semi-colon ◦ If you forget, another prompt line shows up  Either continue the command or…  End it with a semi-colon.
Manipulating MySQL Databases with PHP. PHP and mySQL2 Objectives Connect to MySQL from PHP Learn how to handle MySQL errors Execute SQL statements with.
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.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
SQLite Database. SQLite Public domain database – Advantages Small (about 150 KB) – Used on devices with limited resources Each database contained within.
MySql In Action Step by step method to create your own database.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
INTERNET APPLICATION DEVELOPMENT For More visit:
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
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.
PHP meets MySQL.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
Introduction to Internet Databases MySQL Database System Database Systems.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Database and mySQL Week 07 Dynamic Web TCNJ Jean Chu.
SQLite Android Club SQLite About onCreate Insert Select Update Delete onUpdate.
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.
Chapter 10: The Data Tier We discuss back-end data storage for Web applications, relational data, and using the MySQL database server for back-end storage.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting MySQL – Inserting Data.
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.
Database Objective Demonstrate basic database concepts and functions.
SQLite DB Storing Data in Android RAVI GAURAV PANDEY 1.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
>> Introduction to MySQL. Introduction Structured Query Language (SQL) – Standard Database Language – Manage Data in a DBMS (Database Management System)
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,
Creating E/R Diagrams with SQL Server Management Studio, Writing SQL Queries D0ncho Minkov Telerik School Academy schoolacademy.telerik.com Technical Trainer.
Programming for the Web MySQL Command Line Using PHP with MySQL Dónal Mulligan BSc MA
CHAPTER 9 File Storage Shared Preferences SQLite.
COMP234 – Perl SQL. SQL Syntax Keywords upper case: CREATE TABLE English like syntax Multi-word verbs –INSERT INTO Parentheses and other syntactical guides.
By: Eliav Menachi.  On Android, all application data (including files) are private to that application  Android provides a standard way for an application.
Introduction to Database Programming with Python Gary Stewart
Data Storage in Android Димитър Н. Димитров. Why talk about data? Why not 3D graphics or network connectivity? Data as fundamental term in computer science.
Content Providers.
Chapter 12 Introducing Databases. Objectives What a database is and which databases are typically used with ASP.NET pages What SQL is, how it looks, and.
Making content providers
Cosc 5/4730 Sqlite primer.
Mobile Applications (Android Programming)
SQLite in Android Landon Cox March 2, 2017.
Mobile Applications (Android Programming)
Android Application SQLite 1.
Android Database using SQLite
Database application MySQL Database and PhpMyAdmin
Lecture 8: Database Topics: Basic SQLite Operations.
Developing a Model-View-Controller Component for Joomla Part 3
Mobile Computing With Android ACST 4550 Android Database Storage
Android Developer Fundamentals V2
Charles Severance Single Table SQL.
Department of School of Computing and Engineering
SQLLite and Android.
Mobile Programming Dr. Mohsin Ali Memon.
Presentation transcript:

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/ $ adb shell $ su # mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system # dd if=/sdcard/sqlite3 of=/system/bin/sqlite3 # chmod 4755 /system/bin/sqlite3 # mount -o remount,ro -t yaffs2 /dev/block/mtdblock3 /system

Found Things Record a thing (e.g., audio, picture, text, video, web link, etc.) at a location When someone is near the location, perhaps play the thing. Allow things that are played to be selected in a sophisticate way – Include various information about the things Cache things and get things from the web

Things database idtypefilenameFile state latlongRecorded date Recorded time authorscoreLast playedTag 1Tag 2 1pic1.jpeghere /2/20101:01stephan1005/3/2010treebird Look in database and get thing from nearby and that matched other criteria For now, we will just use near by lat and long

SQLite SQLite is a scaled down version of SQL Data is in tables with rows and columns Each row is a data entry. SQL allows data to be stored and retrieved Basic things (see – Create database – Create table in the database – Insert data into the table – Get data from table (or tables), via query – Theres other stuff, but this is enough for us

Create database and table SQLiteDatabase myDatabase; myDatabase = openOrCreateDatabase( /mnt/sdcard/things.db", SQLiteDatabase.CREATE_IF_NECESSARY, null); – Makes a database called things.db – If no path, then db is in /data/data/ /databases – here we use a specific path so we can examine the db at the command line – Is database already exists, it does not make it Make table – Must specify the column name and type (e.g., integer) – Also, there must be a primary column (a key) such that each entry in this column is unique One way to do this is to include a column that is an integer that autoincrements myDatabase.execSQL("CREATE TABLE IF NOT EXISTS things" + "( id INTEGER PRIMARY KEY AUTOINCREMENT," + " type VARCHAR(40), " + " filename VARCHAR(40), " + " lat INTEGER, " + " long INTEGER);"); Name of table Key is named id and is integer Type is audio, pic, tex, etc. Filename of the thing Location of the thing If IF NOT EXIST is missing, then this will crash if the table already exists

Try it Make function createDatabase Call createDatabase from onCreate Run adb Change to the databases directory ls Run sqlite3 things.db.dump

Add data long newId = myDatabase.insert("things", null, values); Name of table Set of pairs (column name, data for that column) Id of entry ContentValues values = new ContentValues(); values.put("type", "audio"); values.put("filename", "1.mp4"); values.put("lat"," "); values.put("long"," ");

Try it Make function insertData() ContentValues values = new ContentValues(); values.put("type", "audio"); values.put("filename", "1.mp4"); values.put("lat"," "); values.put("long"," "); long newId = myDatabase.insert("things", null, values); Log.d(SQLPlay,insert returned id +newId); Run adb sqllite3 things.db.dump

Add three buttons – Record – Stop – Play Allow record audio, location, internet, camera

Next filename We will save the recorded data with name id.mp4, where id is the id from the database So, to determine the filename, we need to get the next id Or, insert a partial row, get the id and update the row idtypefilenameFile state latlongRecorded date Recorded time authorscoreLast playedTag 1Tag 2 1audio1.mp4here /2/20101:01stephan1005/3/2010treebird 2audionullhere76245/3/20102:02stephan995/4/2010singsong idtypefilenameFile state latlongRecorded date Recorded time authorscoreLast playedTag 1Tag 2 1audio1.mp4here /2/20101:01stephan1005/3/2010treebird 2audio2.mp4here76245/3/20102:02stephan995/4/2010singsong

ContentValues values = new ContentValues(); values.put("type", "audio"); values.put("lat, ); values.put("long, ); long newId = myDatabase.insert("things", null, values); Log.d(SQLPlay","newId="+newId); String filename = newId+".mp4"; ContentValues values2 = new ContentValues(); values2.put("filename", Long.toString(newId)+".mp4"); String wheres[] = new String[1]; wheres[0] = Long.toString(newId); myDatabase.update("things", values2, "id=?", wheres); Make a new column with the filename empty (null) Make file name Make filename column (value pairs like insert) update

location From previous lectures on location Add class attribtues – LocationManager locationManager; – String provider; Make setUpLocation and call from onCreate, after createDatabase public void setUpLocation() { Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setPowerRequirement(Criteria.NO_REQUIREMENT); locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); provider = locationManager.getBestProvider(criteria, true); Location location = locationManager.getLastKnownLocation(provider); String locInfo = String.format("Initial loc = (%f, (%f meters up)", location.getLatitude(), location.getLongitude(), location.getAltitude() ); Log.d("SQLPlay","starting loc: "+locInfo); } Get location

Location when not moving/indoors Get gps lock since last reboot. That way,.getLastKnownLocation doesnt crash Add a random number to location Location location = locationManager.getLastKnownLocation(provider); Random generator = new Random(); int random1 = generator.nextInt( ); int random2 = generator.nextInt( ); int latitude = (int)(location.getLatitude()*1E6+random1); int longitude = (int)(location.getLongitude()*1E6+random2); Put this into getNextfileName function rm things.db Run and make a few files. Dump database

Record sound From previous project, cut record sound and paste into recordSound function Cut and paste stopRecording into stopRecordingButton.onClick – Make buttons nice Run on device Make a few entries adb -d pull /data/data/com.SQLPlay/files c:\audio adb -d pull /data/data/com.SQLPlay/databases c:\audio

Play sound Get location (done) Get database entry that is nearest to current location – Android query – SQL SELECT

Table = things Columns: array of the columns to be returned – E.g., null, returns all columns – E.g., String columns[] = filename; returns the filename {selection selectionArgs} is also know as WHERE (in SQL, one types …. WHERE ~ {selection selectionArgs} – E.g., selection = type=?; String selectionArgs[] = {audio} – E.g., selection = lat<?; String selectionArgs[] = { } – E.g., selection = lat<? AND type=?; String selectionArgs[] = { , audio} Groupby and having are for grouping (we set as null) Orderby is to order the replies (we set as null) Limit controls how many to return (we set as null) – If orderBy is used, then limit can be used to get the first or first few – E.g., orderBy = cost; limit = 1; returns the row with the highest cost public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) Cursor c = myDatabase.query (things, null, null, null, null, null, null, null);

cursor Cursor is used to get the results, which might be emtpy or have several rows, where each row has one or more columns You can scroll through the cursor – Also, you should close the cursor when done – Perhaps use startManagingCursor(c); c.moveToFirst(); while (c.isAfterLast() == false) { String row = new String(); for (int i=0; i<c.getColumnCount(); i++) row += c.getString(i) + " "; Log.d("SQLPlay",row); c.moveToNext(); } c.close();

Try it Make function playAudio and call this function from playButton.onClick Make function, getfilename In playAudio, call getFilename In getFilename, put Cursor c = myDatabase.query (things, null, null, null, null, null, null, null); c.moveToFirst(); while (c.isAfterLast() == false) { String row = new String(); for (int i=0; i<c.getColumnCount(); i++) row += c.getString(i) + " "; Log.d("SQLPlay",row); c.moveToNext(); } c.close(); Run, select play, and look at log.

String selection = lat<? String selectionArgs[] = { }; Try other selections String columns[] = max(lat) Everything else null String selection = lat BETWEEN ? AND ? String selectionArgs[] = {0, }; String selection = lat IN String selectionArgs[] = {somevalue}; Exact match (maybe somevalue can be a set?) String columns[] = min(abs(lat )) Everything else null

nearest But how to get a nearest point? – I dont think it is possible with this type of query rawQuery – Same as SQLite queries. – Androids query is easy, but very limited. rawQuery gives the full power of SQLite – If you know SQL, then you may as well use rawQuery

SQL SELECT SELECT column_name(s) FROM table_name WHERE column_name operator value SELECT * FROM things WHERE lat < Try in sqlite3 In shell, # sqlite3 things.db SELECT * from things ….

Smallest lat – SELECT * FROM things WHERE lat in (SELECT min(lat) ) Nearest lat to SELECT * FROM things WHERE abs(lat ) in (SELECT min(abs(lat ) ) ); – Nearest to La, Lo SELECT * FROM things WHERE abs(lat - La)+abs(long - Lo) in (SELECT min(abs(lat - La)+abs(long - Lo) ) ); Dont forget spaces, -Lo is an invalid string is Lo<0

Back to code Cursor c = myDatabase.rawQuery(…); String la = latitude; String lo = longitude; String ex = abs(lat – la) + abs(long – lo); String Q = SELECT * FROM things WHERE + ex + IN ( SELECT min( + ex + ) FROM things) ; ; Cursor c = myDatabase.rawQuery(Q, []);

File name String Q = SELECT filename FROM things WHERE + ex + IN ( SELECT min( + ex + ) FROM things) ; ; Cursor c = myDatabase.rawQuery(Q, []); String filename = c.getString(0); Log.d(SQLPlay,filename:+filename); Return filename;

Try it in getFilename function Location location = locationManager.getLastKnownLocation(provider); Random generator = new Random(); int random1 = generator.nextInt( ); int random2 = generator.nextInt( ); int latitude = (int)(location.getLatitude()*1E6+random1); int longitude = (int)(location.getLongitude()*1E6+random2); String la = latitude; String lo = longitude; String ex = abs(lat – la) + abs(long – lo); String Q = SELECT filename FROM things WHERE + ex + IN ( SELECT min( + ex + ) FROM things) ; ; Cursor c = myDatabase.rawQuery(Q, []); String filename = c.getString(0); Log.d(SQLPlay,filename:+filename); return filename;

finally In play, paste code to play audio from previous lecture