1 Mobile Computing DataBase and Content Providers Copyright 2014 by Janson Industries EC AssgAssg.

Slides:



Advertisements
Similar presentations
Android – CoNTENT PRoViders
Advertisements

All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
Hello world Follow steps under the sections “Create an AVD” and “Create a New Android Project” at
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
User Interface Android Applications. Activities An activity presents a visual user interface. Each activity is given a default window to draw in. The.
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
Cosc 4730 Android TabActivity and ListView. TabActivity A TabActivity allows for multiple “tabs”. – Each Tab is it’s own activity and the “root” activity.
Android Development (Basics)
CS378 - Mobile Computing Persistence - SQLite. Databases RDBMS – relational data base management system Relational databases introduced by E. F. Codd.
@2011 Mihail L. Sichitiu1 Android Introduction Hello World.
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
SQLite Database. SQLite Public domain database – Advantages Small (about 150 KB) – Used on devices with limited resources Each database contained within.
Introduction to Android Programming Content Basic environmental structure Building a simple app Debugging.
Android development the first app. Andoid vs iOS which is better? Short answer: neither Proponents on both sides For an iOS side, see this article on.
Introducing the Sudoku Example
CS5103 Software Engineering Lecture 08 Android Development II.
Chapter 5: Investigate! Lists, Arrays, and Web Browsers.
1 Mobile Computing Set Up Copyright 2015 by Janson Industries.
Mobile Computing Lecture#08 IntentFilters & BroadcastReceivers.
Favorite Twitter® Searches App Android How to Program © by Pearson Education, Inc. All Rights Reserved.
1 Mobile Computing Monetizing An App Copyright 2014 by Janson Industries.
Hello world Follow steps under the sections “Create an AVD” and “Create a New Android Project” at
Chapter 2: Simplify! The Android User Interface
Android Boot Camp for Developers Using Java, Comprehensive: A Guide to Creating Your First Android Apps Chapter 5: Investigate! Android Lists, Arrays,
Basic Android Tutorial USF’s Association for Computing Machinery.
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.
Package org.androidtown.database.query; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
Chapter 2 The Android User Interface. Objectives  In this chapter, you learn to:  Develop a user interface using the TextView, ImageView, and Button.
Android - Broadcast Receivers
Android Boot Camp for Developers Using Java, 3E
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.
Android Boot Camp for Developers Using Java, Comprehensive: A Guide to Creating Your First Android Apps Chapter 2: Simplify! The Android User Interface.
© 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.
Mobile Software Development ISCG 7424 Department of Computing UNITEC John Casey and Richard Rabeder SQLite and Permissions.
HW#9 Clues CSCI 571 Fall, HW#9 Prototype
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
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.
Chapter 12© copyright Janson Industries Java Server Faces ▮ Explain the JSF framework ▮ SDO (service data objects) ▮ Facelets ▮ Pagecode classes.
Address Book App 1 Fall 2014 CS7020: Game Design and Development.
Mobile Programming Lecture 4 Resources, Selection, Activities, Intents.
Android 基本 I/O. 基本 I/O 介面元件 在此節中主要介紹常見的 I/O 使用者介 面元件 – Button, TextView, 以及 EditText , 學習者可以學會: – Android 的視窗表單設計 res/layout/main.xml – Android SDK –
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
Java for android Development Nasrullah Khan. Using instanceof in Android Development the classes such as Button, TextView, and CheckBox, which represent.
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
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,
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
Chapter 5: Investigate! Lists, Arrays, and Web Browsers.
Making content providers
Chapter 2: Simplify! The Android User Interface
Lecture 3 Zablon Ochomo Android Layouts Lecture 3 Zablon Ochomo
Android Application Development 1 6 May 2018
Android Application SQLite 1.
Android Studio, Android System Basics and Git
Android Database using SQLite
Mobile Application Development Chapter 5 [Persistent Data in Android]
ITEC535 – Mobile Programming
CIS 470 Mobile App Development
CIS 470 Mobile App Development
BMI Android Application will take weight and height from the users to calculate Body Mass Index (BMI) with the information, whether user is underweight,
Mobile Computing With Android ACST 4550 Android Database Storage
CIS 470 Mobile App Development
Android Notifications
CMPE419 Mobile Application Development
Mobile Programming Dr. Mohsin Ali Memon.
CIS 694/EEC 693 Android Sensor Programming
Presentation transcript:

1 Mobile Computing DataBase and Content Providers Copyright 2014 by Janson Industries EC AssgAssg

Copyright 2014 by Janson Industries 2 Objectives ▀ Explain u SQLite u Data Encapsulation u Content providers u Permissions

Copyright 2014 by Janson Industries 3 ▀ DataBase Management System that comes with Android ▀ A database consists of many tables ▀ Tables hold data u In rows/columns (records/fields) SQLite

Copyright 2014 by Janson Industries 4 ▀ To create and manipulate databases and tables, use: u Standard SQL commands u Specialized Android object’s ► SQLiteDatabase ► SQLiteOpenHelper ► Cursor ► ContentValues SQLite

Copyright 2014 by Janson Industries 5 SQLite ▀ Will create a To Do List application ▀ Will allow To Do List items to be entered, displayed, and edited ▀ Will use the Contacts content provider that comes with Android to provide responsible names u More on this a little later

Copyright 2014 by Janson Industries 6 To Do List ▀ Will display an initial screen that allows user to select the function to be performed u Insert a to do list item u Display a to do list item u End to do list app ▀ If insert, user specifies u Priority (1,2,3) u To do item text u Due date u Responsible person

Copyright 2014 by Janson Industries 7

8

9 To Do List ▀ If display u Will display all items text u If user clicks on a item’s text, an edit screen with all the item info will be displayed ▀ Will also display a toast with a success message after inserts and updates

Copyright 2014 by Janson Industries 10

Copyright 2014 by Janson Industries 11 Displays all the item info and allow changes

Copyright 2014 by Janson Industries 12 To Do List ▀ Create a new Android 2.2 project called DBProj u App called ToDoList u Package is my.tdl.com u Activity is Main, layout is main

Copyright 2014 by Janson Industries 13 To Do List n Change Main.java to be an Activity not ActionBarActivity n In manifest, change the application theme : :::::: : :::::: //import android.support.v7.app.ActionBarActivity; import android.app.Activity; : :::: public class Main extends Activity {

Copyright 2014 by Janson Industries <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Choose the function to perform" android:textSize="35sp" /> <CheckBox android:text="Insert" android:onClick="clickHandler" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp"/> <CheckBox android:text="Display" android:onClick="clickHandler" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp"/> <CheckBox android:text="End App" android:onClick="clickHandler" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp"/> 14 main.xml

Copyright 2014 by Janson Industries 15 Test by running in emulator

Copyright 2014 by Janson Industries 16 To Do List ▀ When insert clicked, the Specify To Do List Task screen will be displayed to collect the info ▀ When Insert button clicked u A row with the info will be inserted into a table named task u The Insert/Display/End App screen redisplayed

Copyright 2014 by Janson Industries 17

Copyright 2014 by Janson Industries <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center_vertical" android:text="Specify a To Do List Task" android:textSize="20sp" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:gravity="center_vertical" android:text="Enter the task " android:textSize="15sp" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:text="" android:width="300px"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="Enter a priority of 1, 2, or 3 " android:textSize="15sp"/> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text=" " /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:gravity="center_vertical" android:text="Enter a due date as YYYY/MM/DD " android:textSize="15sp"/> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:text="" android:width="150px" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Insert" android:onClick="onClick" android:layout_gravity="center_horizontal"/> 18 insert.xml

Copyright 2014 by Janson Industries 19 Insert and Display Stubs package my.tdl.com; import android.app.Activity; import android.os.Bundle; public class Insert extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.insert); } package my.tdl.com; import android.app.Activity; import android.os.Bundle; public class Display extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }

Copyright 2014 by Janson Industries 20 Main package my.tdl.com; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.TextView; public class Main extends Activity { Intent intent; String public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } protected void onResume() { super.onResume(); CheckBox icb = (CheckBox) findViewById(R.id.insertCB); CheckBox dcb = (CheckBox) findViewById(R.id.displayCB); /** Erases any checks in the check boxes. */ icb.setChecked(false); dcb.setChecked(false); }

Copyright 2014 by Janson Industries 21 Main public void clickHandler(View target) { switch(target.getId()) { case R.id.insertCB: actionName = "my.tdl.com.Insert"; intent = new Intent(actionName); startActivity(intent); break; case R.id.displayCB: actionName = "my.tdl.com.Display"; intent = new Intent(actionName); startActivity(intent); break; case R.id.finishedCB: finish(); break; }

Copyright 2014 by Janson Industries 22 Manifest <manifest xmlns:android=" package="my.tdl.com" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <application android:allowBackup="true" > <activity android:name=".Main"

Copyright 2014 by Janson Industries 23 Manifest <activity android:name="Insert" android:label="Insert To Do List Task" <activity android:name="Display" android:label="Display To Do List Tasks" n Activity definitions for Insert and Display

Copyright 2014 by Janson Industries 24 To Do List ▀ Run the program ▀ Click Insert check box ▀ Make sure the Insert screen is displayed

Copyright 2014 by Janson Industries 25

Copyright 2014 by Janson Industries 26 If there is a “package definition changed in manifest” msg, on third line of manifest change the package to my.tdl.com

Copyright 2014 by Janson Industries 27 If you get this, click the default button and select the my.tdl.com option

Copyright 2014 by Janson Industries 28 SQLite ▀ Need to create the ToDoList data base and the tasks table ▀ The structure of the tasks table is: u _id INTEGER PRIMARY KEY u Task TEXT u Priority TEXT u CreatedDate TEXT u DueDate TEXT u Responsible TEXT

Copyright 2014 by Janson Industries 29 SQLite ▀ Need a java program to create the DB u A folder called databases will be created in data/data/my.tdl.com on the device/emulator u The DB will be stored in the databases folder ▀ After created, can see the DB in the DDMS perspective

Copyright 2014 by Janson Industries 30 SQLite ▀ To create DB, create Java class (ToDoListDBHelper) as a subclass of SQLiteOpenHelper u It’s constructor will call SQLiteOpenHelper’s constructor u If the DB doesn’t exist, SQLiteOpenHelper’s constructor will call it’s own onCreate method ► onCreate will create the DB

Copyright 2014 by Janson Industries 31 SQLite ▀ SQLiteOpenHelper does all the "heavy lifting" u No only creates the DB, will provide a "writable" version of the DB for our app to use ▀ ToDoListDBHelper must code an onUpgrade method

Copyright 2014 by Janson Industries 32 ToDoListDBHelper package my.tdl.com; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class ToDoListDBHelper extends SQLiteOpenHelper { // Variables to hold metadata about the DB and task table protected static final String DATABASE_NAME = "ToDoList"; protected static final int DATABASE_VERSION = 1; protected final static String TASK_FN = "Task"; protected final static String PRI_FN = "Priority"; protected final static String CREATE_FN = "CreatedDate"; protected final static String DUE_FN = "DueDate"; protected final static String RESP_FN = "Responsible"; protected final static String COMP_FN = "CompletionDate";

Copyright 2014 by Janson Industries 33 ToDoListDBHelper // This SQL statement that will create the table private static final String TABLE_CREATE = "create table TasksTable (" + "_id integer primary key autoincrement, " + TASK_FN + " text, " + PRI_FN + " text, " + CREATE_FN + " text, " + DUE_FN + " text, " + RESP_FN + " text, " + COMP_FN + " text);";

Copyright 2014 by Janson Industries 34 ToDoListDBHelper public ToDoListDBHelper(Context context) { // Creates the database super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { // Creates the tasks table db.execSQL(TABLE_CREATE); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }

Copyright 2014 by Janson Industries 35 Encapsulation n Many terms used to describe: u Transparency u Information hiding u Implementation ignorance n Programmers have an “interface” to an object with no idea of how it works

Copyright 2014 by Janson Industries 36 Encapsulation n For example, driving a car n Someone knows how to drive: u Turn the key u Step on gas pedal u Steer u Step on brake pedal n The driver doesn’t have to know how the car works or any of its internal components

Copyright 2014 by Janson Industries 37 Encapsulation n Many methods and data are hidden from the user/ application n Changes to the class (variables and methods) do not affect users of the class n Data accessible only through publicly defined methods

Copyright 2014 by Janson Industries 38 Data Encapsulation DATA Getters SettersRules Constructors

Copyright 2014 by Janson Industries 39 Encapsulation n If programmers can’t directly access the data, their applications are less likely to screw it up!! n PUBLIC methods comprise the interface n PRIVATE methods for internal functions and non-user fields

Copyright 2014 by Janson Industries 40 How to Encapsulate a File n Define a class for the file (ex. TasksTable) n In the class, define private variables for each field in the file n For each private variable: u Define a getter method u Define a setter with validation functions n Define CRUD functions

Copyright 2014 by Janson Industries 41 How to Encapsulate a File n Define unique functions to return data u All tasks for a particular person u All tasks for a certain priority n Define business functions u Number of tasks closed by day u Number of tasks opened by day

Copyright 2014 by Janson Industries n Define a private variable for each field 42 TasksTable private int ID; private String Task; private String Priority; private String CreatedDate; private String DueDate; private String Responsible; private String CompletionDate;

Copyright 2014 by Janson Industries 43 TasksTable public int getID() { return ID; } public void setID(int iD) { ID = iD; } // Need for updates public String getTask() { return Task; } public void setTask(String task) { Task = task; } public String getPriority() { return Priority; } public void setPriority(String priority) { Priority = priority;} public String getCreatedDate() { return CreatedDate; } public void setCreatedDate(String createdDate) { CreatedDate = createdDate;} public String getDueDate() { return DueDate; } public void setDueDate(String dueDate) { DueDate = dueDate;} public String getResponsible() { return Responsible; } public void setResponsible(String responsible) { Responsible = responsible;} public String getCompletionDate() {return CompletionDate; } public void setCompletionDate(String completionDate) { CompletionDate = completionDate; } n Define getters and setters

Copyright 2014 by Janson Industries n Create pretty easy, plus it creates the helper class that… n …supplies the ToDoList DB (a SQLite DB) that we will read and write to 44 CRUD Functions public TasksTable(Context ctx) { this.context = ctx; DBHelper = new ToDoListDBHelper(context); this.open(); } public TasksTable open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; }

Copyright 2014 by Janson Industries 45 CRUD Functions public long insert() { values.put(TASK_FN, getTask()); values.put(PRI_FN, getPriority()); values.put(CREATE_FN, getCreatedDate()); values.put(DUE_FN, getDueDate()); values.put(RESP_FN, getResponsible()); values.put(COMP_FN, getCompletionDate()); return db.insert(DATABASE_TABLE, null, values); } n Insert and Update require a ContentValues object u It holds the data to be inserted n Each data paired with the field name that will hold the data

Copyright 2014 by Janson Industries n Need some import statements n Also need some other variables n Let’s test 46 CRUD Functions private SQLiteDatabase db; private Context context; private ToDoListDBHelper DBHelper; private ContentValues values = new ContentValues(); private final String DATABASE_TABLE = "TasksTable"; protected final String ID_FN = "ID"; protected final String TASK_FN = "Task"; protected final String PRI_FN = "Priority"; protected final String CREATE_FN = "CreatedDate"; protected final String DUE_FN = "DueDate"; protected final String RESP_FN = "Responsible"; protected final String COMP_FN = "CompletionDate"; package my.tdl.com; import android.content.ContentValues; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase;

Copyright 2014 by Janson Industries n Time to test n Prove the insert works: u Switch to the DDMS perspective u Click on emulator u Expand data/data u Scroll down and expand my.tdl.com F No databases folder 47 To Do List

Copyright 2014 by Janson Industries 48 No databases folder, just lib

Copyright 2014 by Janson Industries n Need to display Insert screen n When Insert button pressed need a java activity (insert) to: u Read screen data u Create TasksTable object u Set the TasksTable object’s task, priority, and due date properties u Insert the data into the table u Display a success msg 49 Insert

Copyright 2014 by Janson Industries package my.tdl.com; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Insert extends Activity implements OnClickListener { TasksTable tt; EditText taskET, priorityET, dueDateET; long insertResult; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.insert); taskET = (EditText) findViewById(R.id.task); // get priorityET = (EditText) findViewById(R.id.priority); // GUI dueDateET = (EditText) findViewById(R.id.DueDate); // fields Button insertBtn = (Button) findViewById(R.id.insert); insertBtn.setOnClickListener(this); // add listener to button tt = new TasksTable(this); // create TasksTable object } 50 Insert

Copyright 2014 by Janson Industries 51 Insert public void onClick(View target) { // Set TasksTable properties tt.setTask(taskET.getText().toString()); tt.setPriority(priorityET.getText().toString()); tt.setDueDate(dueDateET.getText().toString()); // Insert the data insertResult = tt.insert(); // Build msg and display it in a toast String text = "The task '" + tt.getTask() + " was added successfully! Return code was " + insertResult; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(this, text, duration); toast.show(); }

Copyright 2014 by Janson Industries 52

Copyright 2014 by Janson Industries 53 Proof that it worked

Copyright 2014 by Janson Industries 54 n Need to return to the main menu after insert u After the toast is shown add finish(); n For the example, I added a couple of other tasks To Do List

Copyright 2014 by Janson Industries 55 n Allows you to download the DB n Select the DB and click the Pull a file from the device button DDMS Perspecitive

Copyright 2014 by Janson Industries 56

Copyright 2012 by Janson Industries 57 Then specify where to store it

Copyright 2014 by Janson Industries 58 SQLite browser lets you access and manipulate the DB

Copyright 2014 by Janson Industries 59 Download SQLite browser, unzip, run the exe file

Copyright 2014 by Janson Industries 60 File, Open Database, specify ToDoList Then click Browse Data, select TasksTable

Copyright 2014 by Janson Industries 61 n Need a display function u Will display all tasks text n When a task is clicked, will allow user to update all the task info To Do List

Copyright 2014 by Janson Industries 62 Display all the tasks

Copyright 2014 by Janson Industries 63 Display all task info and allow changes

Copyright 2014 by Janson Industries 64 n Going to need: u Read and update functions in TasksTable u Two new screen definitions F display.xml F edit.xml u Change Display.java to F React to a click on a task F Retrieve that tasks info from DB F Invoke TaskEdit and pass DB info via the bundle To Do List

Copyright 2014 by Janson Industries 65 u Create TaskEdit.java to F Display the task info F Update the task F Display a confirmation of the update F Return back to the main menu u Add TaskEdit activity to manifest To Do List

Copyright 2014 by Janson Industries 66 n Update works similarly to insert u Uses a ContentValues object to hold data u Uses the writable ToDoList db object (provided by ToDoListDBHelper) n New requirement: must identify the row to be updated TasksTable Update

Copyright 2014 by Janson Industries 67 n Going to execute an SQL Select statement n Will use the writable db object’s rawQuery method to perform the Select statement n Returns the results in a Cursor object u Essentially a table with rows and columns TasksTable Read

Copyright 2014 by Janson Industries 68 TasksTable import android.database.Cursor; : : : : : public long update() { values.put(TASK_FN, getTask()); values.put(PRI_FN, getPriority()); values.put(CREATE_FN, getCreatedDate()); values.put(DUE_FN, getDueDate()); values.put(RESP_FN, getResponsible()); values.put(COMP_FN, getCompletionDate()); return db.update(DATABASE_TABLE, values, "_id = " + getID(), null ); } public Cursor read() { return db.rawQuery("SELECT * FROM TasksTable ", null); }

Copyright 2014 by Janson Industries 69 display.xml n Create a ListView object called list (holds list of scrollable items) <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" />

Copyright 2014 by Janson Industries 70 edit.xml n Initial LinearLayout and Textview n Followed by a series of horizontal LinearLayouts with components <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:text="" android:gravity="center_vertical" android:layout_gravity="center_horizontal" />

Copyright 2014 by Janson Industries 71 <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change the task " android:gravity="center_vertical" android:layout_gravity="center_vertical" android:textSize="15sp" /> <EditText android:text="" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_gravity="center" android:width="300px"> n For each db field will have text and an entry field

Copyright 2014 by Janson Industries 72 <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content " android:textSize="15sp" android:text="Change the priority (1, 2, or 3) " android:layout_gravity="center_vertical" /> <EditText " android:layout_width="wrap_content" android:layout_gravity="center" android:text=" " android:layout_height="wrap_content"> <LinearLayout android:layout_width="wrap_content " android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change created date (YYYY/MM/DD) " android:gravity="center_vertical " android:layout_gravity="center_vertical" android:textSize="15sp" /> <EditText android:text="" android:layout_height="wrap_content " android:layout_width="fill_parent" android:layout_gravity="center " android:width="150px">

Copyright 2014 by Janson Industries 73 <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change due date (YYYY/MM/DD) " android:gravity="center_vertical" android:layout_gravity="center_vertical" android:textSize="15sp" /> <EditText android:text="" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_gravity="center" android:width="150px"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change/enter person assigned " android:gravity="center_vertical" android:layout_gravity="center_vertical" android:textSize="15sp" /> <EditText android:text="" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_gravity="center" android:width="150px"> edit.xml

Copyright 2014 by Janson Industries 74 <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change/enter finished date (YYYY/MM/DD) " android:gravity="center_vertical" android:layout_gravity="center_vertical" android:textSize="15sp"/> <EditText android:text="" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_gravity="center" android:width="150px"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Update" android:onClick="onClick" android:layout_gravity="center_horizontal" /> edit.xml

Copyright 2014 by Janson Industries 75 n Has to invoke TransTable’s read method n Read returns a Cursor object n Should make sure cursor is managed, startManagingCursor u i.e. Cursor automatically deleted when activity is finished Display.java

Copyright 2014 by Janson Industries 76 n To move between records/rows and retrieve field data, use Cursor methods u To retrieve a field must know the column/field number n Will use a SimpleCursorAdapter to populate the list view u Adapters are classes that make managing list views way easier Display.java

Copyright 2014 by Janson Industries 77 n Requires u The layout be identified u The Cursor object with the data u In a String array (we’ll call it from), the field(s) in the cursor object that are to be retrieved u In an int array (we’ll call it to), the project ids of the GUI component(s) that will display the retrieved data SimpleCursorAdapter

Copyright 2014 by Janson Industries 78 package my.tdl.com; import android.app.Activity; import android.app.ListActivity; import android.widget.SimpleCursorAdapter; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; public class Display extends ListActivity { // Various variables needed to display the list of tasks TextView taskTV; TasksTable tt; Cursor c; SimpleCursorAdapter taskAdapter; String[] from; int[] to; Change Display.java

Copyright 2014 by Janson Industries n onCreate will show the current tasks 79 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display); // Display the list view from = new String[]{"Task"}; // Identify the task field as the source of data to = new int[]{R.id.taskTV}; // Identify taskTV as the target of the data tt = new TasksTable(this); // Create TasksTable object c = tt.read(); // Invoke the read method and store in c startManagingCursor(c); // Let system manage the c // Create the SimpleCursorAdapter object taskAdapter = new SimpleCursorAdapter(this, R.layout.display, c, from, to); setListAdapter(taskAdapter); // Binds adapter to the listview in display layout } Display.java

Copyright 2014 by Janson Industries n onListItemClick is passed both u The location in the list that was clicked u The associated DB record/row id for the clicked item n To read data must first position to the correct row with cursor’s moveToPosition method u c.moveToPosition(rowid); 80 Display

Copyright 2014 by Janson Industries n Then for each field in the row, retrieve the column # with the cursor’s getColumnIndexOrThrow method u int colNum = c. getColumnIndexOrThrow(“fld_name”) n Lastly retrieve the field data with the getString method passing the column number u c.getString(colNum) 81 Display

Copyright 2014 by Janson Industries n Will create a TaskEdit intent and pass the DB data via the intent’s bundle u Mentioned a while ago that bundles used to pass info between activities F Today’s the day we do it 82 Display

Copyright 2014 by Janson Industries n Like the ContentValues object, bundle holds paired data u In this case, the name of the DB field and the value of the field n To write to the bundle use the intents putExtra method 83 Display

Copyright 2014 by Janson Industries 84 protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); c.moveToPosition(position);//Position to correct row in cursor Intent i = new Intent(this, TaskEdit.class);//Create the edit intent i.putExtra("_id", id); //Populate the bundle with the task info //Pass the field name to get the column number, which is used in getString to retrieve //the data from the cursor then the field name and data are written to the bundle i.putExtra(ToDoListDBHelper.TASK_FN, c.getString( c.getColumnIndexOrThrow(ToDoListDBHelper.TASK_FN))); i.putExtra(ToDoListDBHelper.PRI_FN, c.getString( c.getColumnIndexOrThrow(ToDoListDBHelper.PRI_FN))); i.putExtra(ToDoListDBHelper.CREATE_FN, c.getString( c.getColumnIndexOrThrow(ToDoListDBHelper.CREATE_FN))); i.putExtra(ToDoListDBHelper.DUE_FN, c.getString( c.getColumnIndexOrThrow(ToDoListDBHelper.DUE_FN))); i.putExtra(ToDoListDBHelper.RESP_FN, c.getString( c.getColumnIndexOrThrow(ToDoListDBHelper.RESP_FN))); i.putExtra(ToDoListDBHelper.COMP_FN, c.getString( c.getColumnIndexOrThrow(ToDoListDBHelper.COMP_FN))); startActivity(i); //Start the edit task finish(); //End the display task } Display.java

Copyright 2014 by Janson Industries 85 package my.tdl.com; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class TaskEdit extends Activity { EditText taskET, priorityET, createdDateET, dueDateET, respET, compDateET; Button updateBtn; long _id; String task, priority, createdDate, dueDate, responsible, completionDate; Bundle extras; TasksTable tt; TaskEdit n Create various variables needed to display and edit task info

Copyright 2014 by Janson Industries 86 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit); // Retrieve visual components used to display info taskET = (EditText) findViewById(R.id.taskET); priorityET = (EditText) findViewById(R.id.priorityET); createdDateET = (EditText) findViewById(R.id.createdDateET); dueDateET = (EditText) findViewById(R.id.dueDateET); respET = (EditText) findViewById(R.id.respET); compDateET = (EditText) findViewById(R.id.compDateET); // Retrieve the button and the bundle updateBtn = (Button) findViewById(R.id.update); extras = getIntent().getExtras(); TaskEdit

Copyright 2014 by Janson Industries 87 // Get data from bundle and assign to string variables _id = extras.getLong("_id"); task = extras.getString(ToDoListDBHelper.TASK_FN); priority = extras.getString(ToDoListDBHelper.PRI_FN); createdDate = extras.getString(ToDoListDBHelper.CREATE_FN); dueDate = extras.getString(ToDoListDBHelper.DUE_FN); responsible = extras.getString(ToDoListDBHelper.RESP_FN); completionDate = extras.getString(ToDoListDBHelper.COMP_FN); // Put task data into edit text components taskET.setText(task); priorityET.setText(priority); createdDateET.setText(createdDate); dueDateET.setText(dueDate); respET.setText(responsible); compDateET.setText(completionDate); } TaskEdit

Copyright 2014 by Janson Industries 88 public void onClick(View view) { // Create new TasksTable object tt = new TasksTable(this); // Set TasksTable object’s properties to values entered by user tt.setID((int) _id); tt.setTask(taskET.getText().toString()); tt.setPriority(priorityET.getText().toString()); tt.setCreatedDate(createdDateET.getText().toString()); tt.setDueDate(dueDateET.getText().toString()); tt.setResponsible(respET.getText().toString()); tt.setCompletionDate(compDateET.getText().toString()); // Invoke update and display a success msg long updateResult = tt.update(); String text = "The task '" + tt.getTask() + "' was editted successfully! Return code was " + updateResult; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(this, text, duration); toast.show(); finish();//End task edit activity } TaskEdit

Copyright 2014 by Janson Industries 89 Manifest n Need to add a TaskEdit activity inside the application tags n Time to test u Run DBProj, click Display <activity android:name="TaskEdit" android:label="Edit Task"

Copyright 2014 by Janson Industries 90 Click Test payroll program

Copyright 2014 by Janson Industries 91 Initial display Change the text and add a created date

Copyright 2014 by Janson Industries 92 Click Update then display the task

Copyright 2014 by Janson Industries 93 Notice Test text changed and if you click on it…

Copyright 2014 by Janson Industries 94 … created date was saved and retrieved

Copyright 2014 by Janson Industries 95 n Created DBProj such that items can be added and edited in the table Assg

Copyright 2014 by Janson Industries 96 n Basically, a formalized interface to an encapsulated database table n Allows multiple apps access to the stored data n Many already provide a user interface to insert, read, and update Content Providers

Copyright 2014 by Janson Industries 97 Content Providers n Lots of different ones: u Browser u CallLog u Contacts F People F Phones F Photos F Groups u MediaStore u Audio F Albums F Artists F Genres F Playlists

Copyright 2014 by Janson Industries 98 On the Home screen, notice there’s a People icon Click the OK button then double click People icon to start the Contact Content Providers user interface

Copyright 2014 by Janson Industries 99 On the Home screen, click the Phone icon

Copyright 2014 by Janson Industries 100 Click Menu button then New contact

Copyright 2014 by Janson Industries 101 Initial entry screen

Copyright 2014 by Janson Industries 102 Enter some info and click Done A toast will be displayed saying info was saved

Copyright 2014 by Janson Industries 103 Click < button to go to contacts

Copyright 2014 by Janson Industries 104 For this example, will add a couple more contacts

Copyright 2014 by Janson Industries 105 Content Providers n Have an API (application program interface) n An API provides applications access to the content providers data n Lots of rules and objects to work with a content provider

Copyright 2014 by Janson Industries 106 Content Providers n Identified by a URI called an authority name u content://com.compname.provider/ n NotePads URI is: u content://com.google.provider.Note Pad/ n Some native Android providers don’t have a fully qualified name u For example, content://contacts

Copyright 2014 by Janson Industries 107 Content Providers n To identify the underlying DB: u content://com.google.provider.Note Pad/Notes n To identify a particular note : u content://com.google.provider.Note Pad/Notes/14 n Each added element is called a path segment and is identified by a number (1, 2, 3, etc) u So, the provider URI acts like a Web domain name

Copyright 2014 by Janson Industries 108 Content Providers n The Android SDK provides predefined authority name URI variables n For example, instead of creating a URI and specifying this character string: u content://contacts/people/ n You can use u Contacts.People.CONTENT_URI

Copyright 2014 by Janson Industries 109 Content Providers n To insert, need ContentValues and ContentResolver objects n ContentValues holds the data to be inserted (just like with SQLite) u Use the put method to identify the field and specify the value n ContentResolver does the insert u Returns the URI of the new row

Copyright 2014 by Janson Industries 110 Content Providers n To read: u Define/identify the URI u Run a managed query F an inherited Activity method u Retrieve the data from the returned Cursor

Copyright 2014 by Janson Industries 111 Content Providers n To read and display a contact: import android.provider.Contacts; import android.net.Uri; import android.database.Cursor; import android.provider.Contacts.People; : : : : : //This identifies the second contact Uri respPersonUri = Uri.withAppendedPath(Contacts.People.CONTENT_URI, "2"); Cursor c = managedQuery(respPersonUri, null, null, null, null); c.moveToFirst(); int nameColumnIndex = c.getColumnIndex(People.NAME); //This is how to read the field and put the result in a String //String name = c.getString(nameColumnIndex); // This is how to put the name into the responsible ET on the TaskEdit screen respET.setText(c.getString(nameColumnIndex));

Copyright 2014 by Janson Industries 112 Security n Android protects a mobile device’s resources and features u Camera, Contact info, Internet access, Phone, etc. u Complete list at: F ce/android/Manifest.permission.html n An app must have a permission request defined in the manifest file to access these items

Copyright 2014 by Janson Industries 113 Security n Permissions are placed either before or after the application tags like this: n When an app is installed permission is granted/denied : :

Copyright 2014 by Janson Industries 114 Content Providers n Must add permission for contacts <manifest xmlns:android=" package="my.tdl.com" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <application : : : : :

Copyright 2014 by Janson Industries 115

Copyright 2014 by Janson Industries 116 Content Providers n Really what we should do is: u Add a “person responsible” spinner to the insert screen u Populate the spinner with all the contact people so user can just select one u Also, should set a created date when inserted

Copyright 2014 by Janson Industries 117 Content Providers n New spinner with text for insert.xml n Don't forget the permission! <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Assign the task to " android:gravity="center_vertical" android:layout_gravity="center_vertical" android:textSize="15sp"/> <Spinner android:layout_width= "wrap_content" android:layout_height="wrap_content">

Copyright 2014 by Janson Industries 118 Content Providers n In Insert.java import android.widget.Spinner; import android.provider.Contacts.People; import android.widget.SimpleCursorAdapter; import android.database.Cursor; : : : Spinner respSpinner; //Spinner variable for spinner to display contacts String[] from;//Array for field names to be retrieved from Cursor int[] to; //Array to hold GUI component(s) to display contacts Cursor c;//Holds the retrieved contact info : : : respSpinner = (Spinner) findViewById(R.id.respSpinner); Cursor c = managedQuery(People.CONTENT_URI, null, null, null, People.NAME); //Query contacts from = new String[] {People.NAME};//Specify the field to be retrieved to = new int[] {android.R.id.text1};//Specify the text portion of the //spinner as the target for name SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to);//create the adapter respSpinner.setAdapter(adapter);//assign the adapter to the spinner

Copyright 2014 by Janson Industries 119 Run and the spinner will be displayed

Copyright 2014 by Janson Industries 120 Click the drop down button and list is displayed

Copyright 2014 by Janson Industries 121 Date and Time Formatters n A little complicated n First of all, you can get the current date by u Importing java.util.Date u Creating a date object import java.util.Date; : : : Date d = new Date(); System.out.println(d); Results in: Tue May 31 13:11:59 EDT 2011

Copyright 2014 by Janson Industries 122 DateFormat n DateFormat class has predefined formats n To use a DateFormat: u Import DateFormat class u Get a DateFormat instance (getDateInstance) and specify the format to use u Create a date object u Passing the date object as a parameter, use date format object’s format method

Copyright 2014 by Janson Industries Results in: Tue Mar 13 14:38:59 EDT /13/14 Mar 13, 2014 March 13, 2014 Tuesday, March 13, DateFormat import java.text.DateFormat; : : : : Date d = new Date(); DateFormat dfShort= DateFormat.getDateInstance(DateFormat.SHORT); DateFormat dfMed = DateFormat.getDateInstance(DateFormat.MEDIUM); DateFormat dfLong = DateFormat.getDateInstance(DateFormat.LONG); DateFormat dfFull = DateFormat.getDateInstance(DateFormat.FULL); System.out.println(d); System.out.println(dfShort.format(d)); System.out.println(dfMed.format(d)); System.out.println(dfLong.format(d)); System.out.println(dfFull.format(d));

Copyright 2014 by Janson Industries 124 SimpleDateFormat n Allows you to define a unique format n To use a SimpleDateFormat: u Import SimpleDateFormat class u Create a SimpleDateFormat object and specify the format using date format symbols F y – year, s – seconds, a – (AM or PM) F M – month, m – minute F H – hour (0-23), h – hour (1-12) F d – day of month (1-31), D – day of year F z – time zone

Copyright 2014 by Janson Industries Results: 05/31/ :19 PM 1 O'clock PM, Eastern Daylight Time SimpleDateFormat import java.text.SimpleDateFormat; : : : : SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat stf = new SimpleDateFormat("hh:mm a"); SimpleDateFormat st2f = new SimpleDateFormat("h 'O''clock' a, zzzz"); SimpleDateFormat sd2f = new SimpleDateFormat("D"); System.out.println(sdf.format(d)); System.out.println(stf.format(d)); System.out.println(st2f.format(d)); System.out.println(sd2f.format(d));

Copyright 2014 by Janson Industries 126 Extra Credit Assg n Finish Insert such that u The selected name in the spinner is read and inserted into the TasksTable u Add a created date text view and edit view u Put the current date in the edit view in YYYY/MM/DD format u Read the entered created date and insert it into TasksTable

Copyright 2014 by Janson Industries 127 When Insert selected, screen should look like this with current date

Copyright 2014 by Janson Industries 128 Adding this info and clicking Insert…

Copyright 2014 by Janson Industries 129 …means the update screen would look like this

Copyright 2014 by Janson Industries 130 Error You Will Get In a Year n Error generating final archive: Debug certificate expired on XXXX n Android requires that apps be signed n It uses a keystore file called debug.keystore to hold the keys n By default the keystore file is valid for 365 days

Copyright 2014 by Janson Industries 131 Error You Will Get In a Year n Solution: u Navigate to the.android folder in your home directory F C:\Users\youruserid\.android u Delete the debug.keystore file u Go to eclipse and clean all your projects F This creates a new debug.keystore file which will be valid for 365 more days