Adapters. Marco Ronchetti Università degli Studi di Trento - PDF

Description
1 Adapters Marco Ronchetti Università degli Studi di Trento Adapter - AdapterView AdapterView: a view whose children are determined by an Adapter. Adapter: a bridge between an AdapterView and the underlying

Please download to get full document.

View again

of 45
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Information
Category:

Abstract

Publish on:

Views: 33 | Pages: 45

Extension: PDF | Download: 0

Share
Transcript
1 Adapters Marco Ronchetti Università degli Studi di Trento Adapter - AdapterView AdapterView: a view whose children are determined by an Adapter. Adapter: a bridge between an AdapterView and the underlying data for that view. The Adapter: provides access to the data items. makes a View for each item in the data set. 2 Visualizing data ViewGroup AdapterView Adapter data Gallery ListView Spinner ListAdapter CursorAdapter ArrayAdapter 3 Example: ListView + ArrayAdapter 4 public class Adapters1Activity extends ListActivity Extends Activity, public void oncreate(bundle state) { designed to simplify the super.oncreate(savedinstancestate); handling of ListViews. ListView listview = getlistview(); No setcontentview! Data x= new Data(); String[] values= x.getvalues(); ArrayAdapter String adapter = new ArrayAdapter String (this, android.r.layout.simple_list_item_1, values); listview.setadapter(adapter); A default layout, You can see its code here: mydroid/frameworks/base/core/res/ res/layout/ public class Data { private String[] values = new String[] { Red Bull , McLaren , Ferrari , Williams , Toro Rosso , Mercedes , Renault , Force India , Sauber ; public String[] getvalues(){return values; Add non-default row-layout ArrayAdapter String adapter = new ArrayAdapter String (this, R.layout.simple_element, values); simple_element.xml ?xml version= 1.0 encoding= utf-8 ? TextView xmlns:android= http://schemas.android.com/apk/res/android android:layout_width= fill_parent android:layout_height= fill_parent android:padding= 10dp android:textsize= 16sp android:textcolor= #ff0000 android:background= #00ffff /TextView 5 Add a click behaviour listview.setonitemclicklistener(new OnItemClickListener() { public void onitemclick(adapterview ? parent, View view, int position, long id) { // When clicked, show a toast Toast.makeText(getApplicationContext(), x.getmapped(((textview) view).gettext().tostring()), Toast.LENGTH_SHORT).show(); ); Add this fragment to oncreate public class Data { private String[] values = new String[] { Red Bull , McLaren , Ferrari , Williams , Toro Rosso , Mercedes , Renault , Force India , Sauber ; private HashMap String,String hm; Data() { hm=new HashMap String,String (); hm.put( ferrari , Alonso, Massa ); 6 public String[] getvalues(){return values; public String getmapped(string key){ return hm.get(key); Toast A toast is a view containing a quick little message for the user (shown for a time interval). When the view is shown to the user, appears as a floating view over the application. It will never receive focus. It is as unobtrusive as possible, while still showing the user the information you want them to see. setgravity(), setduration(), set Text(), view() 7 Adapter int getcount() How many items are in the data set represented by this Adapter. boolean isempty() true if dataset is empty Object getitem(int k) Get the k-th data item What to do when the data change? void registerdatasetobserver(datasetobserver o) Register an observer that is called when changes happen to the data used by this adapter. void unregisterdatasetobserver(datasetobserver o) Unregister an observer that has previously been registered Class DataSetObserver onchanged() called when the entire data set has changed 8 AdapterView int getfirstvisibleposition() int getlastvisibleposition() Returns the position within the adapter's data set for the first (last) item displayed on screen. getadapter() / setadapter() setonitemclicklistener(adapterview.onitemclicklistener listener) setonitemselectedlistener(adapterview.onitemselectedlistener listener) Object getitematposition(int position) setselection(int position) 9 For more demos and details See Lars Vogel: In the next lectures, we ll discuss Filters and Observers 10 11 Application Context Marco Ronchetti Università degli Studi di Trento The Context An interface to global information about an application environment. It allows accessing application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc. We have seen it in various cases: Activity is subclass of Context new Intent(Context c, Class c); isintentavailable(context context, String action) 12 A global Application Context Is there a simple way to maintain and access the application context from everywhere it s needed? a) Modify the Android Manifest adding the name parameter to the application tag application android:name= mypackage.myapplication /application public class MyApplication extends Application{ private static Context context; public void oncreate(){ super.oncreate(); b) Write the class MyApplication.context = getapplicationcontext(); public static Context getappcontext() { return MyApplication.context; c) Access MyApplication.getAppContext() to get your application context statically from eveywhere. 13 14 Internal Database Marco Ronchetti Università degli Studi di Trento Why an internal database? Useful for easy handling of structured data. 15 The main classes SQLiteOpenHelper responsible for creating, opening, and upgrading a program s database. SQLiteDatabase responsible for communicating changes to the data within the database. Cursor exposes results from a query on a SQLiteDatabase. ContentValues a convenience map to pass values 16 SQLiteOpenHelper SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) context The application context name of the db file (null for an in-memory db) factory for creating (custom) cursor objects, or null for the default version number of the database (starting at 1) 17 SQLiteOpenHelper - lifecycle oncreate onopen onclose getwritabledatabase() NO DB exists? YES onupgrade ondowngrade oncreate() NO DB is cached? getwritabledatabase getreadabledatabase onopen() Cache DB Return Cached reference 18 SQLiteOpenHelper Call close() when the handle to DB is not needed any more (you can reaccess it later). If the DB is opened for reading and you call getwritabledatabase, it gets closed and reopened. 19 Utility class: ContentValues ContentValues (similar to Extras) A key-value map. Methods: void put(string s, #TYPE# val); Object get(string s); #TYPE# getas#type# (String s): getasbyte, getasbytearray, getasfloat, getasinteger, getaslong, getasshort, getasstring Set keyset(), Set valueset() int size(); void clear(); 20 SQLiteDatabase long insert(string table, String nullcolumnhack, ContentValues values) table: the table to insert the row into nullcolumnhack: optional; may be null. Trick to enter an empty row: put in the field the name of the column where a NULL is explicitly inserted. values this map contains the initial column values for the row. The keys should be the column names and the values the column values Returns the ID long replace(string table, String nullcolumnhack, ContentValues values) int delete (String table, String whereclause, String[] whereargs) Es: delete( mytable , A=?, B ?, C ? , new String[] { pippo , 2 , 6 ); means delete * from MyTable where A= pippo , B 2, C 6; returns the number of affected rows void execsql (String sql) where sql is an sql query NOT returning values. 21 SQLiteDatabase Cursor query (String table, String[] columns, String selection, String[] selectionargs, String groupby, String having, String orderby) table The table name to compile the query against. columns A list of which columns to return. Passing null will return all columns selection list of rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table. selectionargs You may include?s in selection, which will be replaced by the values from selectionargs, in order that they appear in the selection. The values will be bound as Strings. groupby how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped. having which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used. orderby How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered. 22 SQLiteDatabase close() DB Status isopen() isreadonly() Transaction support begintransaction() endtransaction() settransactionsuccessful() 23 Utility class: Cursor provides random read-write access to the result set returned by a database query 24 Metadata methods: int getcount() Returns the numbers of rows in the cursor. int getcolumncount() Return total number of columns String getcolumnname(int columnindex) Returns the column name at the given zero-based column index. String [] getcolumnnames() Returns a string array holding the names of all of the columns in the result set in the order in which they were listed in the result. int gettype(int columnindex) Returns data type of the given column's value. FIELD_TYPE_BLOB FIELD_TYPE_FLOAT FIELD_TYPE_INTEGER FIELD_TYPE_NULL FIELD_TYPE_STRING Utility class: Cursor Position check boolean isfirst() boolean isafterlast() boolean isbeforefirst() boolean islast() Position move boolean move(int offset) Move the cursor by a relative amount, forward or backward, from the current position. boolean movetoposition(int position) Move the cursor to an absolute position. boolean movetofirst() Move the cursor to the first row. boolean movetolast() Move the cursor to the last row. boolean movetonext() Move the cursor to the next row. boolean movetoprevious() Move the cursor to the previous row. All the move methods return true If the move was successful 25 Utility class: Cursor void close() closes the Cursor, releasing all of its resources and making it completely invalid. boolean isclosed() return true if the cursor is closed Getter methods double getdouble(int columnindex) float getfloat(int columnindex) int getint(int columnindex) long getlong(int columnindex) short getshort(int columnindex) String getstring(int columnindex) byte[] getblob(int columnindex) All the getter methods return the value of the requested column as the specified type 26 Utility methods in Context String[] databaselist() Returns an array of strings naming the private databases associated with this Context's application package. boolean deletedatabase(string name) Delete an existing private SQLiteDatabase associated with this Context's application package. 27 Input fields 28 Internal Database: an example DB Content Marco Ronchetti Università degli Studi di Trento Derived by Lars Vogel, with modifications ORM - DAO WORLD MODEL UML ORM ERA DAO ARCHITECTURE DB Actual storage FS Data Object 29 Our Activity main.xml ?xml version= 1.0 encoding= utf-8 ? LinearLayout android:orientation= vertical LinearLayout android:orientation= vertical Button android:text= add New android:onclick= onclick / EditText requestfocus / /EditText EditText /EditText Button android:text= delete First android:onclick= onclick / /LinearLayout ListView android:layout_width= fill_parent android:layout_height= wrap_content / /LinearLayout 30 Our Activity package it.unitn.science.latemar; import public class SQLliteActivity extends ListActivity { private PersonDAO public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); dao = new PersonDAO_DB_impl(); dao.open(); List Person values = dao.getallpersons(); // Use the SimpleCursorAdapter to show the // elements in a ListView ArrayAdapter Person adapter = new ArrayAdapter Person (this, android.r.layout.simple_list_item_1, values); setlistadapter(adapter); 31 Our protected void onresume() { dao.open(); protected void onpause() { dao.close(); super.onpause(); // Will be called via the onclick attribute of the buttons in main.xml public void onclick(view view) { ArrayAdapter Person adapter = (ArrayAdapter Person ) getlistadapter(); Person person = null; final EditText tf1 = (EditText) findviewbyid(r.id.edittext1); final EditText tf2 = (EditText) findviewbyid(r.id.edittext2); 32 Our Activity switch (view.getid()) { case R.id.add: String name=tf1.gettext().tostring(); String surname=tf2.gettext().tostring(); person = dao.insertperson(new Person(name,surname)); adapter.add(person); tf1.settext( ); tf2.settext( ); break; case R.id.delete: break; adapter.notifydatasetchanged(); // end of method // end of class if (getlistadapter().getcount() 0) { person = (Person) getlistadapter().getitem(0); dao.deleteperson(person); adapter.remove(person); 33 ORM - DAO WORLD MODEL UML ORM ERA DAO ARCHITECTURE DB Actual storage FS Data Object 34 35 The Object package it.unitn.science.latemar; public class Person { private long id; private String name; private String surname; Person(){ Person(long id, String name, String surname){ this.name=name; this.surname=surname; this.id=-1; // means: not in DB Person(String name, String surname){ this.name=name; this.surname=surname; this.id=id; // means: not in DB public long getid() { return id; public void setid(long id) { this.id = id; public String getname() { return name; public void setname(string name) { this.name = name; public String getsurname() { return surname; public void setsurname(string surname) { this.surname = public String tostring() { return name+ +surname; ORM - DAO WORLD MODEL UML ORM ERA DAO ARCHITECTURE DB Actual storage FS Data Object 36 The DAO interface package it.unitn.science.latemar; import java.util.list; public interface PersonDAO { public void open(); public void close(); public Person insertperson(person person) ; public void deleteperson(person person) ; public List Person getallperson() ; 37 ORM - DAO WORLD MODEL UML ORM ERA DAO ARCHITECTURE DB Actual storage FS Data Object 38 The DB package it.unitn.science.latemar; import android.content.context; import android.database.sqlite.sqlitedatabase; import android.database.sqlite.sqliteopenhelper; import android.util.log; public class MySQLiteHelper extends SQLiteOpenHelper { Define constants public static final String TABLE_PEOPLE = people ; public static final String COLUMN_ID = _id ; public static final String COLUMN_NAME = name ; public static final String COLUMN_SURNAME = surname ; private static final String DATABASE_NAME = contacts.db ; private static final int DATABASE_VERSION = 1; // Database creation sql statement private static final String DATABASE_CREATE = create table + TABLE_PEOPLE + ( + COLUMN_ID + integer primary key autoincrement, + COLUMN_NAME + text not null, + COLUMN_SURNAME + text not null); ; public MySQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); Using default Cursor factory 39 The DB part public void oncreate(sqlitedatabase database) { public void onupgrade(sqlitedatabase db, int oldversion, int newversion) { Log.w(MySQLiteHelper.class.getName(), Upgrading database from version + oldversion + to + newversion + , which will destroy all old data ); db.execsql( drop TABLE IF EXISTS + TABLE_PEOPLE); oncreate(db); 40 The DAO implementation - DB public class PersonDAO_DB_impl implements PersonDAO { private SQLiteDatabase database; private MySQLiteHelper dbhelper; private String[] allcolumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_NAME, public void open() throws SQLException { if (dbhelper==null) dbhelper = new MySQLiteHelper(MyApplication.getAppContext()); database = public void close() { dbhelper.close(); package it.unitn.science.latemar; import Using the code we discussed to access the Global Context 41 The DAO impl. utility methods private ContentValues persontovalues(person person) { ContentValues values = new ContentValues(); values.put(mysqlitehelper.column_name, person.getname()); values.put(mysqlitehelper.column_surname, return values; person.getsurname()); From Object To DB private Person cursortoperson(cursor cursor) { long id = cursor.getlong(0); String name=cursor.getstring(1); String surname=cursor.getstring(2); return new Person(id,name,surname); From DB To Object 42 The DAO impl. data access public Person insertperson(person person) { long insertid = database.insert(mysqlitehelper.table_people, null, persontovalues(person)); // Now read from DB the inserted person and return it Cursor cursor = database.query(mysqlitehelper.table_people, allcolumns, MySQLiteHelper.COLUMN_ID + =? , new String[] { +insertid, null, null, null); cursor.movetofirst(); Person p=cursortoperson(cursor); cursor.close(); return p; 43 The DAO impl. data access public void deleteperson(person person) { long id = person.getid(); //database.delete(mysqlitehelper.table_people, // MySQLiteHelper.COLUMN_ID + = + id, // null); database.delete(mysqlitehelper.table_people, MySQLiteHelper.COLUMN_ID + =? , new String[] { +id); RED version preferred to the BLUE one! 44 The DAO impl. data access public List Person getallpersons() { List Person people = new ArrayList Person (); Cursor cursor = database.query(mysqlitehelper.table_people, cursor.movetofirst(); while (!cursor.isafterlast()) { allcolumns, null, null, null, null, null); Person person = cursortoperson(cursor); people.add(person); cursor.movetonext(); cursor.close(); // Remember to always close the cursor! return people; Select * from people 45
Related Search
Similar documents
View more...
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks