Professional Documents
Culture Documents
LEARN ANDROID
A blog to learn Android
HOME APPLICATIONS
Home Applications
Android default Database engine is Lite. SQLite is a lightweight transactional database engine that occupies small amout of disk storage and memory, so its a perfect choice for creating databases on many mobile operating systems such as Android, iOS. Things to consider when dealing with SQLite: 1. Data type integrity is not maintained in SQLite, you can put a value of a certain data type in a column of another dataype (put string in an integer and vice versa). 2. Referential integrity is not maintained in SQLite, there is no FOREIGN KEY constraints or JOIN statements. 3. SQLite Full Unicode support is optional and not installed by default. In this tutorial we will create a simple database application to store employees data. the DB has: Tables: 1. Employees 2. Dept. Views: 1. ViewEmps: to display employees and their relative departments.
The Constructor:
1 public DatabaseHelper(Context context) { 2 super(context, dbName, null,33); 3 }
Context con: the context attached to the database. dataBaseName: the name of the database. CursorFactory: some times we may use a class that extends the Cursor class to implement some extra validations or operations on the queries run on the database. In this case we pass an instance of CusrsorFactory to return a reference to our derived class to be used instead of the default cursor, In this example we are going to use the standard Cursor Interface to retrieve results, so the CursorFactory parameter is going to be null. Version: the version of the schema of the database. The constructor creates a new blank database with the specified name and version.
26 27 28 29 30 31 }
the method creates tables with columns,a view and a trigger. The method is invoked when the database is created. So we create our table and specify the columns. This method is invoked when the database does not exist on the disk, its executed only once on the same device at the first time the application is run on the device.
This method is invoked when the version number specified in the constructor of the class changes. when you want to append a change to your database you must change the version number in the constructor of the class: so when you pass the constructor a version number of 2:
1 public DatabaseHelper(Context context) { 2 super(context, dbName, null,2); 3 4 // TODO Auto-generated constructor stub
instead of 1:
1 super(context, dbName, null,2);
the application understands that you want to upgrade the database and onUpgrade method will be invoked A typical implementation of this method is to drop the tables and create them again with the additional modifications.
1 db.execSQL("CREATE TABLE "+deptTable+" ("+colDeptID+ " INTEGER PRIMARY KEY , "+ 2 colDeptName+ " TEXT)");
Inserting records:
we insert records to the databse using the following code for example to insert records in the Dept table:
SQLiteDatabase db=this.getWritableDatabase(); ContentValues cv=new ContentValues(); cv.put(colDeptID, 1); cv.put(colDeptName, "Sales"); db.insert(deptTable, colDeptID, cv);
notice that we need to call this.getWritableDatabase() to open the connection with the database forreading/writing. the ContentValues.put has two parameters: Column Name and the value to be inserted. also it is a good practice to close the database after executing statements.
Updating values:
to execute an update statement we have two ways 1. to execute db.execSQL 2. to execute db.update method:
01 public int UpdateEmp(Employee emp) 02 { 03 04 05 SQLiteDatabase db=this.getWritableDatabase(); ContentValues cv=new ContentValues(); cv.put(colName, emp.getName());
06 07 08 09 10 }
cv.put(colAge, emp.getAge()); cv.put(colDept, emp.getDept()); return db.update(employeeTable, cv, colID+"=?", new String []{String.valueOf(emp.getID())});
the update method has the following parameters: 1. 2. 3. 4. String Table: the table to update a value in ContentValues cv: the content values object that has the new values String where clause: the WHERE clause to specify which record to update. String[] args: the arguments of the WHERE clause.
Deleteing rows:
as in update to execute a delete statement we have two ways 1. to execute db.execSQL 2. to execute db.delete method:
1 public void DeleteEmp(Employee emp) 2 { 3 4 5 6 } SQLiteDatabase db=this.getWritableDatabase(); db.delete(employeeTable,colID+"=?", new String [] {String.valueOf(emp.getID())}); db.close();
the delete method has the same parameters as the update method.
Executing queries:
to execute queries there are two methods: 1. Execute db.rawQuery method. 2. Execute db.query method. to execute a raw query to retreive all departments
1 Cursor getAllDepts() 2 { 3 SQLiteDatabase db=this.getReadableDatabase(); Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id, "+colDeptName+" from 4 "+deptTable,new String [] {}); 5
6 7 }
return cur;
the rawQuery method has two parameters: 1. String query: the select statement. 2. String[] selection args: the arguments if a WHERE clause is included in the select statement. Notes: 1. The result of a query is returned in Cursor object. 2. In a select statement if the primary key column (the id column) of the table has a name other than _id then you have to use an alias in the form SELECT [Column Name] as _id cause the Cursor object always expects that the primary key column has the name _id or it will throw an exception .
another way to perform a query is to use a db.query method. a query to select all employees in a certain department from a view would be like this:
1 public Cursor getEmpByDept(String Dept) 2 { 3 4 5 6 7 } SQLiteDatabase db=this.getReadableDatabase(); String [] columns=new String[]{"_id",colName,colAge,colDeptName}; Cursor c=db.query(viewEmps, columns, colDeptName+"=?", new String[]{Dept},null, null, null); return c;
the db.query has the folowing parameters: 1. String Table Name: the name of the table to run the query against. 2. String [ ] columns: the projection of the query i.e the columns to retrieve. 3. String WHERE clause: where clause, if none pass null. 4. String [ ] selection args: the parameters of the WHERE clause. 5. String Group by: a string specifying group by clause. 6. String Having: a string specifying HAVING clause. 7. String Order By by: a string Order By by clause.
Managing Cursors:
Result sets of queries are returned in Cursor objects. there are some common methdos that you will use with cursors: 1. boolean moveToNext(): moves the cursor by one record in the result set, returns false if moved past the last row in the result set.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
2. boolean moveToFirst(): moves the cursor to the first row in the result set, returns false if the result set is empty. 3. boolean moveToPosition(int position): moves the cursor to a certain row index within the boolean result set, returns false if the position is un-reachable 4. boolean moveToPrevious():moves the cursor to the preevious row in the result set, returns false if the cursor is past the first row. 5. boolean moveToLast():moves the cursor to the lase row in the result set, returns false if the result set is empty. there are also some useful methods to check the position of a cursor: boolean isAfterLast(), isBeforeFirst, isFirst,isLast and isNull(columnIndex).
also if you have a result set of only one row and you need to retreive values of certain columns, you can do it like this:
1 public int GetDeptID(String Dept) 2 { 3 4 5 SQLiteDatabase db=this.getReadableDatabase(); Cursor c=db.query(deptTable, new String[]{colDeptID+" as _id",colDeptName},colDeptName+"=?", new String[]{Dept}, null, null, null);
//Cursor c=db.rawQuery("SELECT "+colDeptID+" as _id FROM "+deptTable+" WHERE "+colDeptName+"=?", new String []{Dept}); 6 c.moveToFirst(); 7 8 9 } return c.getInt(c.getColumnIndex("_id"));
we have Cursor.getColumnIndex(String ColumnName) to get the index of a column. then to get the value of a certain column we have Cursor.getInt(int ColumnIndex) method. also there are getShort,getString,getDouble, getBlob to return the value as a byte array. it's a good practice to close() the cursor after using it. Download a sample application on using database in Android from here
Reactions:
This entry was posted on October 4, 2009 at 12:14 pm, and is filed under Cursor, SQL, SQLite . Follow any responses to this post through RSS. You can leave a response, or trackback from your own site.
Written by Anonymous November 29, 2010 5:11 AM
29 COMMENTS:
A little more clear explanation on the foreign reference key would be great!
Hi, we use foreign keys to ensure referential integrity. in this example the requirement is to ensure that we can't insert an employee with a Dept id that does not exist in the Departments table. and since Android's sqlite does not support foreign keys constraints, so we force the same effect using TRIGGERS. I hope it's more clear now, waiting for your reply. thanks
hi, i'm a newbie in using sqlite database with android. can you let me know detail about the sample. I've tried to execute the app but something get wrong when I try to recall back the data that i've inserted into. Thank you very much.
Hi Im also getting an error on calling back the data ive entered. The error seems to occur in method LoadGrid() in GridList.java. It throws the exception that reads: android.database.SQLiteException: no such column EmployeeName while compiling: SELECT _id,EmployeeName, Age, DeptName FROM ViewEmps WHERE DeptName=?
Hi Noah I checked the app and it's working fine. maybe you can change the database version to re-create it to make sure that your db is created successfully
Im a newbie in Android so kindly excuse my questions if they are naive. Ive tried to upgrade the database using the following line: this.onUpgrade(db, 1, 2); But the error still seem sto be there. Any ideas? What could I be doing wrong? Great article by the way!
Hi Noah you are welcome at anytime to ask any question you want. you can upgrade the database by changing the version number of the constructor of the SQLiteOpenHelper super class like this: public DatabaseHelper(Context context) { super(context, dbName, null,new version number);
} I uploaded the DatabaseHelper.java file again so you can check it with the one you have. you can dowload it from here http://dl.dropbox.com/u/2624328/Android%20Pro/2010/October/DatabseHelper.java good luck
Really a great article i have found ever for the understanding of Database working in Android, Having only one word "Awesome" ......thanx
I tried upgrading the db but it does not seem to work. The problem seems to occur in the Sqlite VIEW called ViewEmps. I get the expected output of displaying Employees Entered when I ignore this VIEW and do a normal sql inner join inside method getEmpByDept. Such that the method is now: public Cursor getEmpByDept(String Dept) { SQLiteDatabase db = this.getReadableDatabase(); String[] columns = new String[] { "_id", colName, colAge, colDeptName }; Cursor c=db.rawQuery("SELECT " + employeeTable+ "." + colID + " AS _id," + " " + employeeTable + "."+ colName + "," + " " + employeeTable + "." + colAge + ","+ " " + deptTable + "." + colDeptName + "" + " FROM "+ employeeTable + " JOIN " + deptTable + " ON " + employeeTable+ "." + colDept + " =" + deptTable + "." + colDeptID+" WHERE "+colDeptName+"=\""+Dept+"\"",null);
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
return c; }
Dear Mina Samy, great tutorial.Its very helpful. I want to ask one question. when entering data into database,if the employee name which I entered is already there in database then also second time employee name is added.I mean to say,the same name is accepting multiple times. Can you please provide the solution for accepting emp name only once.When the same emp name is entered then it has to display "name already exists". Thanks in advance. John
Hi, In the real world, employee name can be entered twice. Although rare, there are instances where a company may have 2 employees with the same name. You might want to add a field such as national id number that is unique to every employee. Anyhow, to use EmployeeName, try this: public long checkEmployeeExists(String eName){ SQLiteDatabase db = this.getReadableDatabase(); long employeeExists = -1; try { employeeExists = db.compileStatement( "SELECT COUNT(*) FROM " + DatabaseHelper.employeeTable + " WHERE "+colName+" = " + eName).simpleQueryForLong(); } catch (NullPointerException e) { return -1; } return employeeExists; } The method counts the number of rows in the empTable that have EmployeeName equal to the string passed as a parameter. If the return is not -1, it means that the name already exists.
Sorry guys for being late to respones. @John: the issue you're talking about can be tackled in any database application on any platform by providing a solution similar to what Noah suggested.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
another way is to create a trigger that checks if the new value already exists, if so it throws an error. in this case the SQLiteDB.Insert() method will return -1 instead of the ID of the newly inserted record
I also downloaded the application and get an sqlite no such column exception error regarding missing column name EmployeeName from ViewEmps. Too bad, would have been nice if the application actually, you know, worked
Hi I downloaded the application andfound no errors. anyway here's the declaration of ViewWmps db.execSQL("CREATE VIEW "+viewEmps+ " AS SELECT "+employeeTable+"."+colID+" AS _id,"+ " "+employeeTable+"."+colName+","+ " "+employeeTable+"."+colAge+","+ " "+deptTable+"."+colDeptName+""+ " FROM "+employeeTable+" JOIN "+deptTable+ " ON "+employeeTable+"."+colDept+" ="+deptTable+"."+colDeptID );
hi mina samy i am a newbie to android platform and i found tis article really gud :) but the thing is m also getting the same error saying sql exception like no such column exist .. please provide me the solution as am doing the final year project on android i need it very urgently .. :( btw thank u vry much learnt many things from tis article :)
Hi nitin her's the declaration of ViewEmps db.execSQL("CREATE VIEW "+viewEmps+ " AS SELECT "+employeeTable+"."+colID+" AS _id,"+ " "+employeeTable+"."+colName+","+ " "+employeeTable+"."+colAge+","+ " "+deptTable+"."+colDeptName+""+ " FROM "+employeeTable+" JOIN "+deptTable+ " ON "+employeeTable+"."+colDept+" ="+deptTable+"."+colDeptID );
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
replace with this one and change version number hope it helps
I also get exactly the same error - article is great but it would be nice to get this issue sorted as it seems like quite a few people have ran in to it. Which Android version are you using in the emulator? and which IDE/version are you using? Thanks!
OK guys, it turns out that this has to be ran on 2.2... not 2.1 which is what the project seems to have been built for. Runs on 2.1 perfectly.
The problem is the column names in the view. Just change the creation of the view with this:
db.execSQL("CREATE VIEW "+viewEmps+ " AS SELECT "+employeeTable+"."+colID+" AS _id,"+ " "+employeeTable+"."+colName+" AS EmployeeName,"+ " "+employeeTable+"."+colAge+" AS Age,"+ " "+deptTable+"."+colDeptName+" AS DeptName"+ " FROM "+employeeTable+" JOIN "+deptTable+ " ON "+employeeTable+"."+colDept+" ="+deptTable+"."+colDeptID ); And upgrade version
Lol...this is great stuff, but then for a total fresher plz it would be nice, if like in the explanations, you added in which part of the sdk we code what? other so nice. thx
Hi any idea how i can make a database that can handle and return the following fields when queried. Book name, Book cover, Book description. am tryn to make an e-reader. will be gr8ful for your help.
@Anonymous: you can create a table with the following fields: _id,BookName, BookCover, BookDescription as in this example.
I hope you can post pictures of how the user interface would look like. Thanks.
hello everyone!. I am working on simple social application in which i want to take photo for user as input from gallery not from internet and store it in database and later when user logs in with same username then his/her image should be displayed in viewProfile page. Please help me out....... Thanking You..
Is it possible to see the trigger raise() error message in the LogCat? When I try tripping the trigger, all I see is "error code 19: constraint failed".
Post a Comment
Links to this post
Create a Link Newer PostOlder PostHome Subscribe to: Post Comments (Atom)
Search
SUNPHOS
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Advertise Here
Table layout Organizing widgets in a table is a famous approach in HTML design where you construct a table of a number of rows and cells and distribute t... Android Gallery Control In Android the Gallery control is a selection control that displays items in a horizontal gallery. the items in the gallery appear beside ea... Using View Flipper in Android Suppose you want to display a news bar in your activity. this news bar displays a single news item at a time then flips and shows next item ... Using Themes and Styles in Android In web design we have the concept of Styles and Themes. Styles like Cascading Style Sheets (CSS) define the values of the web controls attri... iPhone-Like Tab bar in Android In a previous post we saw how to use the TabHost to create tabs in Android applications. Also we noticed that the Tabs in Android appear at ...
ABOUT ME
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
BLOG ARCHIVE
o 2012 (2) o 2011 (35) o 2010 (52) December (1) November (1) October (2) How to check if the phone is connected to the Inte... Using SQLite Database with Android September (4) August (5) July (4) June (3) May (5) April (6) March (4) February (8) January (9) o 2009 (3)
LABELS
Absolute Layout (1) Activity (1) AIDL (1) Alert (1) Alternative 3.0 (1) Android 4.0(1) Android Menus (1) Amazon App Store (1) AnalogClock (1) Android(2) Android Structure (1)Android Software 2.2 (1) Android 2.3 (1) Android
Project
Stack (1) Apple (1) Application Resources (1) Assets (1) assets
folder (2) AsyncTask (2) AutoCompleteEditText (1) Browser(1) Button (1) CheckBox (1) Chronometer (2) Color
tools (1) DigitalClock (1) Dimentions Resources(1) DOM Parser (1) drawable folder (1) EditText (1) Emulator(1) error folder (1)Gingerbread (1) Google Nexus One (1) GridLayout (1)Handler (2) Hello
Providers (2) Contest(2) Context Menu (1) Currency Converter (1) Cursor (1) Dalvik Virtual Machine (1) DatePicker (1) DatePickerDialog (1)Development
Sandwich (2) Image Resources (1)ImageButton (1) Images (1) Intent Filters (1) Intents (3)internet connection (1) Introduction to Android (1) iOS
5 (1)iPhone (1) iPhone 3GS (1) JSON (1) layout folder (1) Layout Properties (1)
Layout
Resources (7)Linear
Prime (1) Options
Menu (2) Parsing (3) Photography (1) RadioButton (1)RapidFire (1) Relative Layout (1) Remote Service (1) res folder(2) Resources (1) REST (2) SAX
Parser (1) ScrollView (1)Search (1) Service (2) SharedPreferences (1) signing (1) Slide ME (1) SlidingDrawer (1) SOAP (1) Space (1) Spinner (1) SQL(1) SQLite (1) src Menu (1) SUNPHOS (2) TabHost (1) Table Layout (1)Tabs (2) TabWidget (1) TextView (1) Themes (1)Threading folder (1) ViewFlipper (1)We-Pad (1) web folder (1) SSL (1) String Resources (1) Styles(1) Sub
(3) TimePicker (1) TimePickerDialog (1) Toast(1) ToggleButton (1) UI (1) values
VISITORS
FOLLOWERS LISTED IN
Top Stories
DISCLAIMER
All information provided in this blog is provided "as-is". It's based only on personal experience. Author will not compensate you in any way whatsoever if you ever happen to suffer a loss/inconvenience/damage because of/while making use of information in this blog.
o o o o
Mystique theme by digitalnature | Converted by Theme Craft | Click Here! | The SEO King | The Blog Resource |