Download presentation
Presentation is loading. Please wait.
Published byCoral Nichols Modified over 9 years ago
1
1 Mobile Computing DataBase and Content Providers Copyright 2014 by Janson Industries EC AssgAssg
2
Copyright 2014 by Janson Industries 2 Objectives ▀ Explain u SQLite u Data Encapsulation u Content providers u Permissions
3
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
4
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
5
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
6
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
7
Copyright 2014 by Janson Industries 7
8
8
9
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
10
Copyright 2014 by Janson Industries 10
11
Copyright 2014 by Janson Industries 11 Displays all the item info and allow changes
12
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
13
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 : :::::: android:theme="@android:style/Theme.Black" : :::::: //import android.support.v7.app.ActionBarActivity; import android.app.Activity; : :::: public class Main extends Activity {
14
Copyright 2014 by Janson Industries <LinearLayout xmlns:android="http://schemas.android.com/apk/res/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:id="@+id/insertCB" android:text="Insert" android:onClick="clickHandler" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp"/> <CheckBox android:id="@+id/displayCB" android:text="Display" android:onClick="clickHandler" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp"/> <CheckBox android:id="@+id/finishedCB" android:text="End App" android:onClick="clickHandler" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp"/> 14 main.xml
15
Copyright 2014 by Janson Industries 15 Test by running in emulator
16
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
17
Copyright 2014 by Janson Industries 17
18
Copyright 2014 by Janson Industries <LinearLayout xmlns:android="http://schemas.android.com/apk/res/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:id="@+id/task" 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:id="@+id/priority" 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:id="@+id/DueDate" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:text="" android:width="150px" /> <Button android:id="@+id/insert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Insert" android:onClick="onClick" android:layout_gravity="center_horizontal"/> 18 insert.xml
19
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); }
20
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 actionName; @Override 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); }
21
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; }
22
Copyright 2014 by Janson Industries 22 Manifest <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.tdl.com" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.Black" > <activity android:name=".Main" android:label="@string/app_name">
23
Copyright 2014 by Janson Industries 23 Manifest <activity android:name="Insert" android:label="Insert To Do List Task" android:theme="@android:style/Theme.Black"> <activity android:name="Display" android:label="Display To Do List Tasks" android:theme="@android:style/Theme.Black"> n Activity definitions for Insert and Display
24
Copyright 2014 by Janson Industries 24 To Do List ▀ Run the program ▀ Click Insert check box ▀ Make sure the Insert screen is displayed
25
Copyright 2014 by Janson Industries 25
26
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
27
Copyright 2014 by Janson Industries 27 If you get this, click the default button and select the my.tdl.com option
28
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
29
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
30
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
31
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
32
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";
33
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);";
34
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) { }
35
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
36
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
37
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
38
Copyright 2014 by Janson Industries 38 Data Encapsulation DATA Getters SettersRules Constructors
39
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
40
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
41
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
42
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;
43
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
44
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; }
45
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
46
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;
47
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
48
Copyright 2014 by Janson Industries 48 No databases folder, just lib
49
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
50
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
51
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(); }
52
Copyright 2014 by Janson Industries 52
53
Copyright 2014 by Janson Industries 53 Proof that it worked
54
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
55
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
56
Copyright 2014 by Janson Industries 56
57
Copyright 2012 by Janson Industries 57 Then specify where to store it
58
Copyright 2014 by Janson Industries 58 SQLite browser lets you access and manipulate the DB
59
Copyright 2014 by Janson Industries 59 http://web.fscj.edu/Janson/CIS2930 Download SQLite browser, unzip, run the exe file
60
Copyright 2014 by Janson Industries 60 File, Open Database, specify ToDoList Then click Browse Data, select TasksTable
61
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
62
Copyright 2014 by Janson Industries 62 Display all the tasks
63
Copyright 2014 by Janson Industries 63 Display all task info and allow changes
64
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
65
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
66
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
67
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
68
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); }
69
Copyright 2014 by Janson Industries 69 display.xml n Create a ListView object called list (holds list of scrollable items) <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/android:list" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/taskTV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" />
70
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="http://schemas.android.com/apk/res/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" />
71
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:id="@+id/taskET" 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
72
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:id="@+id/priorityET " 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:id="@+id/createdDateET" android:text="" android:layout_height="wrap_content " android:layout_width="fill_parent" android:layout_gravity="center " android:width="150px">
73
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:id="@+id/dueDateET" 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:id="@+id/respET" android:text="" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_gravity="center" android:width="150px"> edit.xml
74
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:id="@+id/compDateET" android:text="" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_gravity="center" android:width="150px"> <Button android:id="@+id/update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Update" android:onClick="onClick" android:layout_gravity="center_horizontal" /> edit.xml
75
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
76
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
77
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
78
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
79
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
80
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
81
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
82
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
83
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
84
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
85
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
86
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
87
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
88
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
89
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" android:theme="@android:style/Theme.Black">
90
Copyright 2014 by Janson Industries 90 Click Test payroll program
91
Copyright 2014 by Janson Industries 91 Initial display Change the text and add a created date
92
Copyright 2014 by Janson Industries 92 Click Update then display the task
93
Copyright 2014 by Janson Industries 93 Notice Test text changed and if you click on it…
94
Copyright 2014 by Janson Industries 94 … created date was saved and retrieved
95
Copyright 2014 by Janson Industries 95 n Created DBProj such that items can be added and edited in the table Assg
96
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
97
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
98
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
99
Copyright 2014 by Janson Industries 99 On the Home screen, click the Phone icon
100
Copyright 2014 by Janson Industries 100 Click Menu button then New contact
101
Copyright 2014 by Janson Industries 101 Initial entry screen
102
Copyright 2014 by Janson Industries 102 Enter some info and click Done A toast will be displayed saying info was saved
103
Copyright 2014 by Janson Industries 103 Click < button to go to contacts
104
Copyright 2014 by Janson Industries 104 For this example, will add a couple more contacts
105
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
106
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
107
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
108
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
109
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
110
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
111
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));
112
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 http://developer.android.com/referen ce/android/Manifest.permission.html n An app must have a permission request defined in the manifest file to access these items
113
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 : :
114
Copyright 2014 by Janson Industries 114 Content Providers n Must add permission for contacts <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.tdl.com" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <application android:icon="@drawable/ic_launcher" : : : : :
115
Copyright 2014 by Janson Industries 115
116
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
117
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:id="@+id/respSpinner" android:layout_width= "wrap_content" android:layout_height="wrap_content">
118
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
119
Copyright 2014 by Janson Industries 119 Run and the spinner will be displayed
120
Copyright 2014 by Janson Industries 120 Click the drop down button and list is displayed
121
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
122
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
123
Copyright 2014 by Janson Industries Results in: Tue Mar 13 14:38:59 EDT 2014 3/13/14 Mar 13, 2014 March 13, 2014 Tuesday, March 13, 2014 123 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));
124
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
125
Copyright 2014 by Janson Industries Results: 05/31/2011 01:19 PM 1 O'clock PM, Eastern Daylight Time 151 125 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));
126
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
127
Copyright 2014 by Janson Industries 127 When Insert selected, screen should look like this with current date
128
Copyright 2014 by Janson Industries 128 Adding this info and clicking Insert…
129
Copyright 2014 by Janson Industries 129 …means the update screen would look like this
130
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
131
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.