CMPE419 Mobile Application Development

Slides:



Advertisements
Similar presentations
Programming with Android: Data management
Advertisements

CC SQL Utilities.
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.
 data/data-storage.html#pref data/data-storage.html#pref 
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.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
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
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
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.
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.
Data Storage: Part 2 (File System). Internal Storage versus External Storage Internal storage − for private data –By default, files saved to the internal.
CSE 486/586, Spring 2012 CSE 486/586 Distributed Systems Recitation.
SQLite Android Club SQLite About onCreate Insert Select Update Delete onUpdate.
Nilesh Singh Local Data Storage option Android provides several options for you to save persistent application data. - Shared preferences - Creation.
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.
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.
CHAPTER 9 File Storage Shared Preferences SQLite.
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.
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,
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)
ASP.NET Programming with C# and SQL Server First Edition
Content provider.
Cosc 5/4730 Sqlite primer.
Android Content Providers & SQLite
Mobile Applications (Android Programming)
Content Providers And Content Resolvers
SQL – Python and Databases
Data Storage: Part 2 (File System)
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
Mobile Applications (Android Programming)
Android Application SQLite 1.
Reactive Android Development
Android Database using SQLite
Mobile Application Development Chapter 5 [Persistent Data in Android]
SQL – Application Persistence Design Patterns
Mobile Computing With Android ACST Android Database Storage Part 2
CMPE419 Mobile Application Development
CS371m - Mobile Computing Persistence - SQLite.
Mobile Computing With Android ACST 4550 Android Database Storage
Computer Science Projects Database Theory / Prototypes
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.
Mobile Programming Dr. Mohsin Ali Memon.
SQL – Application Persistence Design Patterns
Presentation transcript:

CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren 2017-2018 SPRING Computer Engineering Department CMPE419 AU

File & SQLite

Read/Write to Internal Storage Files Read/Write to Internal Storage This area of storage is sort of private to the application. It is always available to the application and gets purged when the app is uninstalled by the user. Internal storage refers to the hard drive on device. Internal storage gives you the ability to prevent other applications from accessing the files you save and are tied directly to your app. Files stored in /data/data/packagename/files/filename.txt. There are few modes for file access MODE_PRIVATE – create a new file or overwrite one if it already exists with the same name MODE_APPEND – create the file if it doesn’t exist and allow you to append to the file if it does exist MODE_WORLD_READABLE - file is readable by any other application MODE_WORLD_WRITEABLE - file is writeable by any other application

Internal storage can be accessed using the Context methods  openFileInput(String filename), which returns a FileInputStream object, or  openFileOutput(String filename, int mode), which returns a FileOutputStream.

Write to file in internal storage String FILE_NAME = "file.txt"; try { FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE); fos.write(someText.toString().getBytes()); fos.close(); } catch (Exception e) { e.printStackTrace(); }

Read from file in internal storage try { String text=""; FileInputStream fin = openFileInput(filename); int size=fin.available(); byte[] buffer=new byte[size]; fin.read(buffer); fin.close(); text=new String(buffer); contents = new ArrayList<String>(Arrays.asList(text.split("\n"))); } catch (IOException e) { e.printStackTrace(); }

Example

Overview Many well known applications and Internet browsers use SQLite due to its very small size (~250 Kb).  Also it is not an external program, and is instead bundled with the application using it.  Google Chrome / Firefox’s Caching / Skype  Most mobile platforms including IOS, Android, Blackberry  Especially for Audio/Video files, SMS/MMS storage, Contacts, and Calendar Events  Even Mac OS X 10.4 onward on Desktops/Laptops

In Android OS SQLite is Open Source, and completed embedded within the Android OS.  It does not require any additional setup.   Database is automatically managed for you! Supports standard SQL syntax and data types (TEXT [String], INTEGER [Long], REAL [Double]).  Other data types must be converted. Individual Applications are assigned their own SQLite databases which are inherently private. You can share them with a ‘ContentProvider’ Object to other applications if you wish to share the Database.  (Ex: An app which uses your contact list, or your music library)

Using SQLite in Android Architecture (1) import android.database.sqlite to use the library - Extend the SQLiteOpenHelper class and overwrite the methods - Overwrite onCreate() method to create the database - Overwrite onUpgrade() method to update the schema any time it is modified - Pass in SQLiteDatabase object to these methods, which represents the database itself - getReadableDatabase() provides read-only access to the database - getWriteableDatabase() lets you read and write to/from the database

Using SQLite in Android Architecture (2) - Primary keys are denoted by the _id identifier- You can directly execute SQL statements via the execSQL() method.   - Example:     public static void onCreate(SQLiteDatabase database) {         database.execSQL("create table todo "             + "(_id integer primary key autoincrement, "             + "category text not null, " + "summary text not null,"             + " description text not null);";);     }

Using SQLite in Android Architecture (3) - SQLiteDatabase allows methods to open the database connection, perform queries and query updates, and close the database [insert() update() and delete()]   - You can define keys and values for queries via the ContentValues object.  This is necessary for Insert and Update calls. Delete only requires the Row Number. - The Key is the Column, and the Value is the selected key's value.  For instance a Key may be Age with a Value of 25.

Using SQLite in Android Architecture (4)  - Insert the specified values into DB_TABLE at the next available incremented row.    public long createTodo(String priority, String title, String description) {         ContentValues values = createContentValues(priority, title,                 description);         return db.insert(DB_TABLE, null, values);     }  - Update the specified values in DB_TABLE at the specified rowId, and check if the new data is different from the old data.     public boolean updateTodo(long rowId, String priority, String title,             String description) {         ContentValues values = createContentValues(priority, title,                 description);         return db.update(DB_TABLE, values, KEY_ROWID + "=" + rowId, null) >                     0;     }  

Using SQLite in Android Architecture (5)  - Delete the specified row from DB_TABLE if it exists.     public boolean deleteTodo(long rowId) {         return db.delete(DB_TABLE, KEY_ROWID + "=" + rowId, null) > 0;     }  

Query Methods (1) - Two methods... query() and rawQuery(), both return a Cursor object, essentially a pointer to one or more rows in a List-like format. - Cursors always point to one row which is one reason SQLite is so efficient.  You can use various Iterators such as moveToFirst() and moveToNext() to traverse the list, and isAfterLast() to check if data is remaining.  Specific columns can be accessed as well by index. - rawQuery() is more MySQL-like in nature:   Cursor getAllDepts() { SQLiteDatabase db=this.getReadableDatabase(); Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id, " +colDeptName+" from "+deptTable,new String [] {}); return cur; } Two parameters: - String query: The select statement - String[] selection args: The arguments if a WHERE clause is included in the select statement

Query Methods (2) - query() has the following parameters: String Table Name: The name of the table to run the query against String [ ] columns: The projection of the query, i.e., the columns to retrieve, null means all columns. String WHERE clause: where clause, if none pass null String [ ] selection args: The parameters of the WHERE clause String Group by: Filter for grouping rows. String Having:  Additional filter for rows. String Order By by:  Ordering for the rows.   public Cursor getEmpByDept(String Dept) { SQLiteDatabase db=this.getReadableDatabase(); String [] columns = new String[]{"_id",colName, colAge,colDeptName}; Cursor c=db.query(viewEmps, columns, colDeptName+"=?", new String[]{Dept}, null, null, null); return c; }

Android Program - Utilized Foundation Activity classes to create a simple personal task manager application. - Information is permanently saved (Until Deleted) on a SQLite Database - Can Insert new Tasks, Update existing Tasks, and Delete. - Two main screens, Overview and Details Screen.   

List of Classes (1) - Overview Activity class shows the list of all tasks - Details Activity class shows the currently selected task. - Table class with the onCreate() and onUpgrade() methods - onPause() and onResume() are implemented in the Details Activity and save the state on minimizing/exiting the Application, and restore it upon resuming. - Helper class which extends SQLiteOpenHelper and calls the Table class methods - Adapter class to allow for queries, creates, updates.  open() method opens the database by calling the helper class.  Creates and Updates are handled via the ContentValues class  

List of Classes (2) - XML Resources are especially important. - Strings are defined in res/values/strings.xml - Task Priority is defined in res/values/priority.xml - Menus are defined in res/menu - listmenu.xml defines the Option Menu - todo_list.xml is the layout for the view of the entire task list. - todo_row.xml is the layout for the individual task rows of the list - todo_edit.xml is the layout of the current task being viewed for an insert/update. - res/drawable folders are for icons within the application. - Last but not least... androidManifest.xml file contains some very important information such as Version requirements, entrypoint for the ‘Main’ class, Application names, requirements, icons, permissions.  

Example: In this example we will learn How to create a Table Add a data to table Get a data from a table

First Lets create a Class that contains basic informations related with your database: package com.example.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class Data extends SQLiteOpenHelper{ private static final String Database_name="Student"; private static final int Version=1; public Data(Context c) {super(c,Database_name,null,Version); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE Mydata(name TEXT, surname TEXT);"); public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXIST Mydata"); }}

Columns: Name - Surname Table with name Mydata Columns: Name - Surname Deletes Mydata table

Define Objects for Views Define an Object for DataBase Create an Object for Database Create Links to Views Listener for save button Method that takes to parameters If there is an error close your table

Listener for show button Method for reading from database

Create db object and prepare your database for writing Create cv1 object for defining values that will be inserted into database Use insertOrThrow() or insert() methods to insert values to db

Define columns that you will read Create db object and prepare your database for reading Create reading object that halps you to move in columns 5 null values:  where clause, where clause values, groupby, having, orderby. 

EXAMPLE: Add-Delete-View Step 1: Design your GUI

Step 2: Create Database controller Java Code (StuDB.Java)

Step 3: Create View Links between JAVA and HML codes:

Step 4: Button Listeners

Reference Links: http://www.sqlite.org/ - Official Website http://en.wikipedia.org/wiki/SQLite - Wikipedia Entry for SQLite for general information. http://www.codeproject.com/KB/android/AndroidSQLite.aspx - Sample SQLite Queries http://developer.android.com/guide/index.html - Android Developer Guide http://www.stackoverflow.com - The Google of Programming