android sqlite database by rz rasel 1st edition

49
ANDROID DINNER TIME HAND NOTE RZ RASEL

Upload: rz-rasel

Post on 07-Apr-2016

231 views

Category:

Documents


5 download

DESCRIPTION

Android sqlite database by rz rasel 1st edition

TRANSCRIPT

Page 1: Android sqlite database by rz rasel 1st edition

Android

dinner Time HAnd noTe

rz rAsel

Page 2: Android sqlite database by rz rasel 1st edition

Dinner Time Hand Note®Android

Rz Rasel

Android

Rz Rasel

Page 3: Android sqlite database by rz rasel 1st edition

Dinner Time Hand Note®Android

DESIGN AND DEVELOPMENT

1st Edition

Rz Rasel

Android

Rz Rasel

Page 4: Android sqlite database by rz rasel 1st edition

Copyright © by Rz Rasel

All rights reserved. No part of this book may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechani-cal methods, without the prior written permission of the writer, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the writer, addressed “Attention: Permissions Coordinator,” at the address below.

[email protected]

1st Edition: August 2014

Cover Illustration Copyright © by Rz Rasel ([email protected])Cover design by Rz Rasel.Book design by Rz RaselEditing by Rz RaselChapter opening illustrations © Rz Rasel

Android

Rz Rasel

Page 5: Android sqlite database by rz rasel 1st edition

AuthorRz Rasel

Others

Rz Rasel (Rashed - Uz - Zaman) is a Software Engineer. Back-end and Front-end developer web experience. Also working in PHP, Android, Database like Sql, MySql, Sqlite. Web developer, Web designer, and blogger. Contact e-mail:- [email protected].

CREDITSI would like to thanks all of them.

I would like to thanks all of them.

Android

Rz Rasel

Page 6: Android sqlite database by rz rasel 1st edition

Rz Rasel (Rashed - Uz - Zaman) Software Engineer. Software developer, Software designer, System designer, Database designer, Web developer, Web designer, and blogger born in Ban-gladesh, and now living in Bangladesh.

Rz Rasel unearthed the World Wide Web and started creating web sites many years. Working in software frim in bangladesh as android developer, web developer with system analysis and design, database design. Write blogs in google blogger, WordPress (https://arzrasel.word-press.com). A few years later, Rz Rasel created his first blog (https://arzrasel.wordpress.com).

In his spare time, he enjoys to write story, poem. You can visit his home page at https://arz-rasel.wordpress.com or e-mail him at [email protected].

Rz Rasel

AbOuT AuTHORAndroid

Rz Rasel

Page 7: Android sqlite database by rz rasel 1st edition

“This is a great quick reference book that presents content and examples in a way that it serves both beginners and intermediate users alike.” Here you will find corrections, tips, clari-fications, and samples related to the ANDROID reference book. You are encouraged, if you find an error or something that needs clarification, to post a comment to the blog or e-mail so it can be addressed in a post and fixed for later versions (that’s what I call wishful thinking).

Rz Rasel

AuTHOR’S NOTEAndroid

Rz Rasel

Page 8: Android sqlite database by rz rasel 1st edition

Get in touch with writer

WordPress blog:- https://arzrasel.wordpress.com Facebook:- https://www.facebook.com/rzprogrammingFacebook:- https://www.facebook.com/groups/merzrasel/Facebook:- https://www.facebook.com/groups/rzprogrammer/E-mail:- [email protected]

Rz Rasel

GET IN TOuCHAndroid

Rz Rasel

Page 9: Android sqlite database by rz rasel 1st edition

0102

03

CONTENTS

SQLITE AND RELATIONAL DATAbASEWhat is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . . 15Features of SQLite . . . . . . . . . . . . . . . . . . . . . . . . . 15Advantages of using SQLite . . . . . . . . . . . . . . . . . . . . . 15

GETTING STARTED WITH SQLITE DATAbASEWhat is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . . 18Getting Started with SQLite. . . . . . . . . . . . . . . . . . . . . 18SQLite Java Classes . . . . . . . . . . . . . . . . . . . . . . . . 19Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19SQLite Database . . . . . . . . . . . . . . . . . . . . . . . . . . 19SQLite Open Helper . . . . . . . . . . . . . . . . . . . . . . . . 19

SQLITE DATAbASE FOR ANDROID DEVELOPERSGetting Started . . . . . . . . . . . . . . . . . . . . . . . . . . 21What is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . . 21A Quick Review of Database Fundamentals . . . . . . . . . . . . . 21The Chess Tournament Database . . . . . . . . . . . . . . . . . . 22Designing the Database Schema . . . . . . . . . . . . . . . . . . 22Working with Tables . . . . . . . . . . . . . . . . . . . . . . . . 22Populating Tables with Data Records . . . . . . . . . . . . . . . . 23Querying Tables for Results with SELECT . . . . . . . . . . . . . . 24Using Column Aliases and Calculated Columns . . . . . . . . . . . . 24Altering Data in Tables . . . . . . . . . . . . . . . . . . . . . . . 24Using Foreign Keys and Composite Keys . . . . . . . . . . . . . . . 25Querying Across Multiple Tables Using JOIN . . . . . . . . . . . . . 26Executing More Complex Queries . . . . . . . . . . . . . . . . . . 26Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

SQLITE DATAbASE CRuD OPERATIONSWhat is Sqlite in Android? . . . . . . . . . . . . . . . . . . . . . 29Quick explanation of the API classes and methods involved . . . . . . 29SQLiteDatabase . . . . . . . . . . . . . . . . . . . . . . . . . . 29execSQL() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

04

Android

Rz Rasel

Page 10: Android sqlite database by rz rasel 1st edition

05

rawQuery() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29SQLiteOpenHelper . . . . . . . . . . . . . . . . . . . . . . . . . 29onCreate() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29onUpgrade() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30CRUD Operations . . . . . . . . . . . . . . . . . . . . . . . . . 30Insert operation . . . . . . . . . . . . . . . . . . . . . . . . . . 30Update Operation . . . . . . . . . . . . . . . . . . . . . . . . . 30Delete Operation . . . . . . . . . . . . . . . . . . . . . . . . . . 31Read Operation . . . . . . . . . . . . . . . . . . . . . . . . . . 31Raw Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

ANDROID SQLITE DATAbASE AND CRuD OPERATIONIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Application Background . . . . . . . . . . . . . . . . . . . . . . 33Application User Interface (UI) Design. . . . . . . . . . . . . . . . 33Using the Code . . . . . . . . . . . . . . . . . . . . . . . . . . 35Application Setup . . . . . . . . . . . . . . . . . . . . . . . . . 40Codes All Together . . . . . . . . . . . . . . . . . . . . . . . . . 44RzStdManage.java . . . . . . . . . . . . . . . . . . . . . . . . . 44mani.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47string.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

[email protected] Free To Ask Question You May Have

CONTENTSAndroid

Rz Rasel

Page 11: Android sqlite database by rz rasel 1st edition

Android

Rz Rasel

Page 12: Android sqlite database by rz rasel 1st edition

Android

Rz Rasel

Page 13: Android sqlite database by rz rasel 1st edition

Android

Rz Rasel

Page 14: Android sqlite database by rz rasel 1st edition

SQLITE AND RELATIONAL DATAbASEWhat is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . . 15Features of SQLite . . . . . . . . . . . . . . . . . . . . . . . . . 15Advantages of using SQLite . . . . . . . . . . . . . . . . . . . . . 15

[email protected] Free To Ask Question You May Have

01

CONTENTSAndroid

Rz RaselChapter - 01Page - 14

Page 15: Android sqlite database by rz rasel 1st edition

SQLite is used in most of the applications which need less complicated relational database. SQLite is embedded in every Android device and it provides phenomenal support to perform database operations in Android via in built Android APIs.

What is SQLite?

SQLite is an Open Source database. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. The database requires limited memo-ry at runtime (approx. 250 KByte) which makes it a light weight database to embed into other runtimes. SQLite supports the data types TEXT (like String in Java), INTEGER (like long in Java) and REAL (like double in Java). All other types must be converted into one of these fields before getting saved in the database. SQLite itself does not validate if the types written to the col-umns are actually of the defined type, e.g. you can write an integer into a string column and vice versa.

SQLite is different from most other SQL database engines in that its primary design goal is to be simple:

• Easy and simple to administer• Easy and simple to operate• Easy and simple to embed in a larger program• Easy and simple to maintain and customize

Features of SQLite

• Zeroconfiguration– SQLite does not need to be Installed as there is no setup proce-dure to use it.

• Serverless– SQLite is not implemented as a separate server process. With SQLite, the process that wants to access the database reads and writes directly from the database files on disk as there is no intermediary server process.

• Stable Cross-PlatformDatabase File– The SQLite file format is cross-platform. A database file written on one machine can be copied to and used on a different machine with a different architecture.

• SingleDatabaseFile– An SQLite database is a single ordinary disk file that can be lo-cated anywhere in the directory hierarchy.

• Compact– When optimized for size, the whole SQLite library with everything enabled is less than 400KB in size.

Advantages of using SQLite

Below are the advantages of using SQLite:• There is no file parsing and no need to generate code to read/write/update the file.• Content can be accessed and updated using powerful SQL queries, greatly reducing the

complexity of the application code.• Extending the file format for new capabilities in later releases is a simple as adding new

tables or new columns to existing tables.• Diverse content which might otherwise be stored as a “pile-of-files” can be encapsulated

into a single disk file.

Android

Rz RaselChapter - 01Page - 15

Page 16: Android sqlite database by rz rasel 1st edition

• The content can be viewed using third-party tools like Toad.• The application file is portable across all operating systems, 32-bit and 64-bit and big-

and little-endian architectures.• The application only has to load as much data as it needs, rather than reading the entire

application file and holding a complete parse in memory. Startup time and memory con-sumption are reduced.

• Small edits only overwrite the parts of the file that change, not the entire file, thus im-proving performance and reducing wear on SSD drives.

• Content is updated continuously and automically so that there is no work lost in the event of a power failure or crash.

• Performance problems can often be resolved using CREATE INDEX rather than redesign-ing, rewriting, and retesting application code.

[email protected] YOu’VE GOT SuGGESTIONS FOR IMPROVEMENTS I’D LOVE TO SEE. DON’T HESI-

TATE.IF IT’S HELP YOu PLEASE LEAVE A COMMENT AND LET ME KNOW. I’D LOVE TO

HEAR.FEEL FREE TO SEND MORE FEEDbACK OR QuESTION YOu MAY HAVE.

������������z������������

Android

Rz RaselChapter - 01Page - 16

Page 17: Android sqlite database by rz rasel 1st edition

GETTING STARTED WITH SQLITE DATAbASEWhat is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . . 18Getting Started with SQLite. . . . . . . . . . . . . . . . . . . . . 18SQLite Java Classes . . . . . . . . . . . . . . . . . . . . . . . . 19Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19SQLite Database . . . . . . . . . . . . . . . . . . . . . . . . . . 19SQLite Open Helper . . . . . . . . . . . . . . . . . . . . . . . . 19

[email protected] Free To Ask Question You May Have

02

CONTENTSAndroid

Rz RaselChapter - 02Page - 17

Page 18: Android sqlite database by rz rasel 1st edition

If you’re just getting started as an Android app developer, it won’t be long before you need to call on the power of databases to bring your applications to the next level. Some apps are almost entirely data-driven while others simply need to store small amounts of data such as a user’s high score in a game you created.

The importance of a persistent data storage solution within the Android OS is readily apparent because of the unconventional life cycle of an Android application. At any time, the Android runtime could terminate application components to free up resources. Without proper imple-mentation of SQLite into your application, the risk of data loss is very real.

What is SQLite?

SQLite is a relational database management system (RDBMS). What makes SQLite unique is that it is considered an embedded solution. Most database management system such as Oracle, MySQL, and SQL Server are standalone server processes that run independently.

SQLite is actually a library that is linked into applications. All database operations are handled within the application through calls and functions contained in the SQLite li-brary. This is great news while you’re learning to use SQLite because it makes it much easier to manipulate even large databases when compared to more conventional database solutions.

In case you’re interested, SQLite is actually written in C and contained within a Java-based “wrapper” provided by the Android SDK.

SQLite does rely on Structured Query Language (SQL); the same language used by most other RDBMSs. If you’re already familiar with SQL from another database system, you have a serious head start using SQLite because you will find that most query commands are struc-tured exactly the same way.

Getting Started with SQLite

The easiest way to understand SQLite is to start using it. Since Android comes with SQLite preinstalled, you can create an interactive environment by running an instance of the Android Virtual Device (AVD) emulator.

You can start an AVD session using the popular Eclipse IDE. Once started, you can connect a command prompt window to the emulator using the following ADB (Android Debugging Bridge) command:

adb –e shell

The “-e” flag tells the ADB tool to look for an emulator rather than a physical Android device. SQLite databases are stored in database files specific to the application that is running. If you have an Android application with the package name of “com.rzrasel.myDBapp,” the SQLite database for this application would be located at:

/data/data/com.rzrasel.myDBapp/databases/mydatabase.db

The name of the database in this example is “mydatabase.db” but it could be anything you choose to name it. So for the purposes of this example, change directories in the ADB shell and create a subdirectory hierarchy so you can start experimenting with SQLite. It should look something like this:

cd /data/data

mkdir com.rzrasel.myDBapp

cd com.rzrasel.myDBapp

mkdir databases

Android

Rz RaselChapter - 02Page - 18

Page 19: Android sqlite database by rz rasel 1st edition

cd databases

Once you have created this hierarchy correctly, you can initialize the interactive SQLite tool using this command:

sqlite3 ./mydatabase.db

Now you are ready to start entering SQL commands to create, modify, and delete table data from your SQLite database.

SQLite Java Classes

Remember that SQLite is written in C and wrapped in Java by the Android SDK. This wrapper is comprised of a set of Java classes that interact directly with the SQLite database manage-ment system.

Cursor

The Cursor class provides access to the results of a database query. For example, if you use the SQL SELECT operation, you could potentially have multiple returns from within the data-base. Cursor allows you to step through these results which can then be accessed from within the application code.

SQLite Database

This class is the actual interface between your application code and the SQL database.

It includes functions to perform SQL-based operations such as INSERT, DELETE, QUERY, and RAWQUERY (a SQL query statement that returns results in the form of a Cursor object).

SQLite Open Helper

This helper class is designed to make creating and updating databases easier. Please note that this class must be subclassed within the code of your application and include the onCreate() and onUpgrade() callback methods.

Although these classes may seem a little confusing, this approach is certainly easier to un-derstand than conventional RDbMS interfaces and because SQLite is so lightweight, even if your code isn’t perfect you shouldn’t have any problems creating functional databases for your Android applications.

The fact remains that unless you are making only the most basic of Android applications, you need data management. SQLite makes it easy to incorporate powerful database features that provide your users with a much more interactive experience.

[email protected] YOu’VE GOT SuGGESTIONS FOR IMPROVEMENTS I’D LOVE TO SEE. DON’T HESI-

TATE.IF IT’S HELP YOu PLEASE LEAVE A COMMENT AND LET ME KNOW. I’D LOVE TO

HEAR.FEEL FREE TO SEND MORE FEEDbACK OR QuESTION YOu MAY HAVE.

������������z������������

Android

Rz RaselChapter - 02Page - 19

Page 20: Android sqlite database by rz rasel 1st edition

SQLITE DATAbASE FOR ANDROID DEVELOPERSGetting Started . . . . . . . . . . . . . . . . . . . . . . . . . . 21What is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . . 21A Quick Review of Database Fundamentals . . . . . . . . . . . . . 21The Chess Tournament Database . . . . . . . . . . . . . . . . . . 22Designing the Database Schema . . . . . . . . . . . . . . . . . . 22Working with Tables . . . . . . . . . . . . . . . . . . . . . . . . 22Populating Tables with Data Records . . . . . . . . . . . . . . . . 23Querying Tables for Results with SELECT . . . . . . . . . . . . . . 24Using Column Aliases and Calculated Columns . . . . . . . . . . . . 24Altering Data in Tables . . . . . . . . . . . . . . . . . . . . . . . 24Using Foreign Keys and Composite Keys . . . . . . . . . . . . . . . 25Querying Across Multiple Tables Using JOIN . . . . . . . . . . . . . 26Executing More Complex Queries . . . . . . . . . . . . . . . . . . 26Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

[email protected] Free To Ask Question You May Have

03

CONTENTSAndroid

Rz RaselChapter - 03Page - 20

Page 21: Android sqlite database by rz rasel 1st edition

Android applications can store application data in SQLite databases. Here we learn how SQLite databases are designed and manipulated. We begin designing and using a simple SQLite data-base to manage chess tournament scores. Also here a brief overview of how SQLite databases work. This knowledge will then be used in future development tutorials to implement data-base-driven Android applications.

Getting Started

Android applications can create and manipulate their own private SQLite relational databases. Developers can also inspect and modify databases on a given Android emulator or device us-ing the sqlite3 command-line tool provided as part of the Android SDK tool called Android Debug bridge (adb).

Here we assume that you have some understanding of relational databases, in theory, not require any tools; it’s more a theoretical exercise.

However, if you are planning to develop Android applications which rely upon SQLite databas-es, you will need to install the tools necessary for Android development, such as the Android SDK and the Eclipse IDE.

What is SQLite?

SQLite is a lightweight relational database engine. SQLite is fast and has a small footprint, making it perfect for Android devices. Instead of the heavyweight server-based databases like Oracle and Microsoft SQL Server, each SQLite database is stored within a single file on disk. Android applications can choose to store private application data in a SQLite database.

Note: If you’re familiar with SQL, then SQLite will be very easy to pick up. SQLite is basi-cally a stripped-down SQL database engine for embedded devices. For specific information

about SQLite and its features, functionality, and limitations, see the SQLite online documen-tation (http://www.sqlite.org/).

A Quick Review of Database Fundamentals

A database is simply a structured way of storing data in a persistent fashion. Data is stored in tables. A table has columns with different datatypes. Each row in a table represents a data record. You may find it helpful to think of a table like an Excel spread-sheet. For an object oriented programming perspective, each table in a database often repre-sents an object (represented by a class). Each table column represents a class attribute. Each record in a table represents a specific instance of that object.

Let’s look at a quick example. Let’s say you have a company database with a table called Em-ployee. The Employee table might have five typed columns: EmployeeID (number), FirstName (string), LastName (string), Title (string) and Salary (number). You could then add a record to the data base for an employee named “Rz Rasel” and a separate record for an employee named “Avishek”.

Data within a database is meant to be inspected and manipulated. Data within a table can be:

• Added (using the INSERT command)• Modified (using the UPDATE command)• Removed (using the DELETE command)

Android

Rz RaselChapter - 03Page - 21

Page 22: Android sqlite database by rz rasel 1st edition

You can search for specific data within a database using query. A query (using the SELECT command) may involve one table, or multiple tables. To create a query, you must specify the tables, data columns, and data values of interest using SQL command language. Each SQL command is terminated with a semicolon (;).

The Chess Tournament Database

The best way to truly understand how SQLite databases function is to work through a simple example, so let’s do so. Let’s pretend that we have an application that keeps track of player scores from a casual chess tournament. Player scores are recorded and then, at the end of a series of matches, the winner is determined. Each player’s overall tournament score is calcu-lated from their performance on:

• Four warm-up heats (weight: 10% of overall score each)• One semi-final (weight: 25% of overall score)• One final (weight: 35% of overall score)

Note: For the tournament, player scores could be based upon a formula that factors in the time it took to win the game and the type and number of pieces left on the board at the

end of the game. This way, a strong player will receive a high score for losing few powerful pieces and winning the game quickly. Perhaps style and attitude are included by the judges

to encourage fun, light play. How scores are calculated is really not important to how we define our database; we just store them in the database. For simplicity, we will assume that

scores are based on a scale of 0–100.

Designing the Database Schema

A database schema is simply the definition of the structure of the database in terms of tables, data columns and such. The schema for our tournament database is quite simple:

The Tournament Scores database schema has three tables:

• The Players table contains player information.• The Games table contains information about each game and how much it counts toward

the player’s overall tournament score.• The Game Results table contains all players’ game scores.

SQLite3 has support for the following common datatypes for columns:

• INTEGER (signed integers)• REAL (floating point values)• TEXT (UTF-8 or UTF-16 string; encoded using database encoding)• BLOB (data chunk)

Once you’ve determined which columns are necessary for each table, you’re ready to create some tables within your database schema.

Working with Tables

Let’s begin by creating the Players table. This table requires a unique player id to reference

Android

Rz RaselChapter - 03Page - 22

Page 23: Android sqlite database by rz rasel 1st edition

each player. We can make this the primary key (to uniquely identify a record in this table) and set its autoincrement attribute. Autoincrement means that each time a new player record is added, the record will get a new, unique player id. We also want to store the first and last name of each player-no nulls allowed.

Here we can use the CREATE TABLE SQL statement to generate the Players table:

CREATE TAbLE players( id INTEGER PRIMARY KEY AuTOINCREMENT, fname TEXT NOT NuLL, lname TEXT NOT NuLL);

The Games table is very similar. We need a unique game id to reference each game. We also want a friendly name for each game and a weight value for how much the game counts to-wards the player’s final tournament score (as a percentage). Here’s the SQL statement to create the Games table:

CREATE TAbLE games( id INTEGER PRIMARY KEY AuTOINCREMENT, gamename TEXT, weight REAL DEFAuLT .10 CHECK (weight<=1));

You can also delete tables using the DROP TABLE statement. For example, to delete the Games table, use the following SQL command:

DROP TAbLE games;

Populating Tables with Data Records

Before we move on, let’s add some data to these tables. To add a record to the Players table, you need to specify the column names and the values in order. For example, the following SQL statement uses the INSERT command to add a record for chess player “Rz Rasel”:

INSERT into players (fname, lname) VALUES(‘Rz’, ‘Rasel’);

While we’re add it, we’ll add two more players: Avishek Ahmed (a very pitiful chess player) and Garry Kasparov (perhaps the best chess player ever). At the same time, we need to add a bunch of records to the Games table. First we add the semi-final, which counts for 25 percent of the player’s tournament score:

INSERT into games (gamename, weight) VALUES(‘Semi-Final’, .25);

Then we add a couple warm-up heats, which use the default weight of 10 percent:

INSERT into games (gamename) VALUES(‘Warm-up Heat 1’);

Finally, we add a final worth 35 percent of the total tournament score:

Android

Rz RaselChapter - 03Page - 23

Page 24: Android sqlite database by rz rasel 1st edition

INSERT into games (gamename, weight) VALUES(‘Final’, .35);

Querying Tables for Results with SELECT

How do we know the data we’ve added is in the table? Well, that’s easy. We simply query for all rows in a table using a SELECT statement:

SELECT * FROM games;

This returns all records in the Games table:

id gamename weight-- ------------ -------1 Semi-Final 0.252 Warm-up Heat 1 0.13 Warm-up Heat 2 0.14 Warm-up Heat 3 0.15 Warm-up Heat 4 0.16 Final 0.35

using Column Aliases and Calculated Columns

We can also create our own columns and alias them. For example, we can create a column alias called PlayerName that is a calculated column: It’s the player’s first and last names con-catenated using the || operator, separated by a space:

SELECT fname||’ ‘|| lname AS PlayerName, id FROM players;

This query produces the following results:

PlayerName id------------- --Rz Rasel 1Avishek Ahhmed 2Garry Kasparov 3Parvez Rashid 4

Altering Data in Tables

Avishek’s (player id 2) last name is spelled incorrectly. To update the Players table to reflect the correct spelling, you can use the UPDATE command:

uPDATE playersSET lname=’Ahmed’ WHERE playerid = 2;

You can delete rows from a table using the DELETE function. For example, to delete the record we just updated:

DELETE FROM players WHERE playerid=3;

You can delete all rows in a table by not specifying the WHERE clause:

Android

Rz RaselChapter - 03Page - 24

Page 25: Android sqlite database by rz rasel 1st edition

DELETE FROM players;

using Foreign Keys and Composite Keys

Now that we have our Players and Games all set up, let’s create the Game Results table. This is a more complicated table. The Game Results table pairs up player ids from the Players table with game ids from the Games table and then lists the score that the player earned for the specific game. Columns, which link to other tables in this way, are often called foreign keys. We want unique player-game pairings, so we create a composite primary key from the player and game foreign keys, to uniquely identify a Game Results record. Lastly, we enforce that the scores are whole numbers between 0 and 100.

CREATE TAbLE game_results( playerid INTEGER REFERENCES players(id), gameid INTEGER REFERENCES games(id), score INTEGER CHECK (score<=100 AND score>=0), PRIMARY KEY (playerid, gameid));

Note: SQLite does not enforce foreign key constraints, but you can set them up anyway and enforce the constraints by creating triggers.

Now it’s time to insert some data to the Game Results table. Let’s say “Rz Rasel” (player id 1) received a score of 82 points on the semi-final (game id 1). You could use the following SQL command to insert the appropriate record into the Game Results table:

INSERT into game_results (playerid, gameid, score) VALUES(1, 1, 82);

Now let’s assume the tournament is played and the scores are added to the Game Results ta-ble. “Rz” is a good player, Avishek is a terrible player, and Garry always plays a perfect game. Once the records have been added to the Game Results table, we can perform a SELECT * command to list all records in the table, or we can specify columns explicitly like this:

SELECT playerid, gameid, score FROM game_results;

Here are the results from this query:

playerid gameid score--------- -------- ------1 1 821 2 881 3 781 4 901 5 851 6 942 1 102 2 602 3 502 4 552 5 452 6 65

Android

Rz RaselChapter - 03Page - 25

Page 26: Android sqlite database by rz rasel 1st edition

3 6 1003 5 1003 4 1003 3 1003 2 1003 1 100

As you can see, this listing is not particularly “human-readable”.

Querying Across Multiple Tables using JOIN

Wouldn’t it be more helpful if the names of the players and Games were shown instead of their numeric ids? Querying and combining data in SELECT statements is often handled by performing a JOIN with multiple table sources; there are different kinds of JOINS. When you work with multiple tables, you need to specify which table that a column belongs to (especially when columns are named the same, such as with all these different id columns). You can refer to columns by their column name or by their table name, then a dot (.), and then the column name.

Let’s relist the player scores again, only this time, include the name of the game and the name of the player. Also, we limit our results only to the score for the Final (game id 6):

SELECTplayers.fname||’ ‘|| players.lname AS PlayerName, games.gamename, game_results.scoreFROM game_resultsJOIN players ON (players.id = game_results.playerid)JOIN games ON (games.id = game_results.gameid)WHERE gameid=6;

which gives us the following results (you could leave off the WHERE to get all Games):

PlayerName gamename score------------------ -------------- -----Rz Rasel Final 94Avishek Ahmed Final 65Garry Kasparov Final 100

Executing More Complex Queries

The sky’s the limit when it comes to the queries you could perform here. For our example, the most important query is the one that tells us who won the tournament.Here is the final query for calculating the tournament rankings:

SELECTplayers.fname||’ ‘|| players.lname AS PlayerName,SuM((games.weight * game_results.score)) AS TotalWeightedScoreFROM game_resultsJOIN players ON (players.id = game_results.playerid)JOIN games ON (games.id = game_results.gameid)GROuP bY game_results.playeridORDER bY TotalWeightedScore DESC;

This query gathers information from several different tables using JOINs and calculates the tournament results in a readable way. So let’s look at what this query does:

Android

Rz RaselChapter - 03Page - 26

Page 27: Android sqlite database by rz rasel 1st edition

• Each player’s full name is displayed as the first result column (calculated from their first and last name)

• Each player’s tournament score is displayed as the second result column (calculated from the weighted scores of all games played by a given player)

• The result records are listed in descending order based upon the tournament scores (first place, second place, etc.)

The results from this query are shown below:

PlayerName TotalWeightedScore------------- ----------------------Garry Kasparov 100.0Rz Rasel 87.5Avishek Ahmed 46.25

Conclusion

This concludes our exploration of a simple SQLite database example: a chess tournament da-tabase. Hopefully you’ve reacquainted yourself with relational database concepts like tables, records, and queries and familiarized yourself with many of the commonly used SQLite com-mands. Finally, you’ve walked through the design and usage of an example database. Now that you’ve got a handle on how SQLite databases work, you’re ready to use them within your Android applications.

[email protected] YOu’VE GOT SuGGESTIONS FOR IMPROVEMENTS I’D LOVE TO SEE. DON’T HESI-

TATE.IF IT’S HELP YOu PLEASE LEAVE A COMMENT AND LET ME KNOW. I’D LOVE TO

HEAR.FEEL FREE TO SEND MORE FEEDbACK OR QuESTION YOu MAY HAVE.

������������z������������

Android

Rz RaselChapter - 03Page - 27

Page 28: Android sqlite database by rz rasel 1st edition

Android

Rz RaselChapter - 04Page - 28

04

CONTENTS

SQLITE DATAbASE CRuD OPERATIONSWhat is Sqlite in Android? . . . . . . . . . . . . . . . . . . . . . 29Quick explanation of the API classes and methods involved . . . . . . 29SQLiteDatabase . . . . . . . . . . . . . . . . . . . . . . . . . . 29execSQL() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29rawQuery() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29SQLiteOpenHelper . . . . . . . . . . . . . . . . . . . . . . . . . 29onCreate() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29onUpgrade() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30CRUD Operations . . . . . . . . . . . . . . . . . . . . . . . . . 30Insert operation . . . . . . . . . . . . . . . . . . . . . . . . . . 30Update Operation . . . . . . . . . . . . . . . . . . . . . . . . . 30Delete Operation . . . . . . . . . . . . . . . . . . . . . . . . . . 31Read Operation . . . . . . . . . . . . . . . . . . . . . . . . . . 31Raw Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

[email protected] Free To Ask Question You May Have

Page 29: Android sqlite database by rz rasel 1st edition

Here we will perform CRUD operations by creating our own DatabaseHelper class. This android sqlite database example application will store student information like id, name and phone number inside our sqlite table.

What is Sqlite in Android?

SQLite is an opensource relational database that stores data in android device. Nor-mal SQL (Structured Query Language) can be used to access SQLite database.

We are going to store list of students inside our database. Here you will learn to perform all CRUD operations. i.e. performing create, read, update and delete operations using SQLite database in android.

Quick explanation of the API classes and methods involved

SQLiteDatabase

SQLiteDatabase is an Android class which has methods to create, delete, execute SQL com-mands, and perform other common database management tasks. Here we are using exec-SQL() and rawQuery() methods of SQLiteDatabase class to execute SQL.

execSQL()

execSQL() is a method of SQLiteDatabase Class which is used to execute SQL statements.

rawQuery()

rawQuery() is a method of SQLiteDatabase Class which executes SQL statements and re-turns Cursor.

SQLiteOpenHelper

For adding SQLite database connectivity in android, we need to create a separate class for da-tabase. Here, we will name it DatabaseHelper, now this DatabaseHelper class must implement SQLiteOpenHelper which provides various methods to interact with database.

Snippet 1:

public class DatabaseHelper extends SQLiteOpenHelper{}

DatabaseHelper Class contains 2 most important methods i.e. onCreate and onupdate.

onCreate()

onCreate() This method gets called when the database is created for the first time. Tables would be created inside this method.

Snippet 2:

@Override public void onCreate(SQLiteDatabase db) { // Create students table db.execSQL(CREATE_TABLE_STUDENTS);

Android

Rz RaselChapter - 04Page - 29

Page 30: Android sqlite database by rz rasel 1st edition

}

onupgrade()

onupgrade() This method allows you to upgrade your database. You can update an existing database, drop existing tables and recreate it via onCreate() method.

Snippet 3:

@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // drop table if exists or if database is upgraded db.execSQL(“DROP TABLE IF EXISTS “ + CREATE_TABLE_STUDENTS); onCreate(db); }

CRuD Operations

Let us learn about CRUD operations for our android sqlite database application. Inside our DatabaseHelper class we will be adding methods for CRuD operations.

Insert operation

Insert operation For Inserting values to database we need to save data into content values. ContentValues allows defining key-values pair. The key represents the table column name and the value represents the content corresponding to that column.

Snippet 4:

SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(column1, value1); values.put(column2, value2); values.put(column3, value3); values.put(column4, value4); // insert row in table long insert = db.insert(TABLE_NAME, null, values);

update Operation

Update Operation To update existing record in your android sqlite database table you need to execute the following method.

Snippet 5:

db.update(TABLE_NAME, content_values, WHERE_CLAUSE, WHERE_ARGUMENTS);

• First argument takes the name of the table.• Second argument takes a new record. Here we pass ContentValues object which con-

tains data corresponding to each column in key value pair. So, all the columns which need to get updated are provided in ContentValues object as a key-value pair.

• Third argument specifies the where clause i.e the condition. For example, update the student name where student id is 13. Here where clause is the “id=”.

• Fourth argument takes the value corresponding to where clause. For the above ex-ample it is 13.

Android

Rz RaselChapter - 04Page - 30

Page 31: Android sqlite database by rz rasel 1st edition

Delete Operation

The Delete Operation takes three arguments. First is the table name, second is the where clause and the third is the value corresponding to that where clause.

Snippet 6:

db.delete(TABLE_NAME, WHERE_CLAUSE, WHERE_ARGUMENTS);

Read Operation

Read Operation To read values from android sqlite database table. We execute select opera-tion on database and we get multiple rows as a result. We assign those rows to cursor. Cursor points to one row at a time and in this way we fetch the required data.

Raw Query

Raw Query This query directly accepts SQL as a input. You can directly pass SQL statement to SQLiteDatabase for execute that query.

Snippet 7:

db.rawQuery(sql_statement, null);

Now coming back to cursor, we assign result of select statement to cursor and manipulate the data.

Snippet 8:

String selectQuery = “SELECT * FROM TABLE_NAME”;Cursor c = db.rawQuery(selectQuery, null); //check if query result is not null.if(c != null)c.moveToFirst(); String col1 = c.getString(c.getColumnIndex(column_name));int col2 = c.getInt(c.getColumnIndex(column_name));

You can use loop to fetch all results by moveToNext() method of cursor.

[email protected] YOu’VE GOT SuGGESTIONS FOR IMPROVEMENTS I’D LOVE TO SEE. DON’T HESI-

TATE.IF IT’S HELP YOu PLEASE LEAVE A COMMENT AND LET ME KNOW. I’D LOVE TO

HEAR.FEEL FREE TO SEND MORE FEEDbACK OR QuESTION YOu MAY HAVE.

������������z������������

Android

Rz RaselChapter - 04Page - 31

Page 32: Android sqlite database by rz rasel 1st edition

05

CONTENTS

ANDROID SQLITE DATAbASE AND CRuD OPERATIONIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Application Background . . . . . . . . . . . . . . . . . . . . . . 33Application User Interface (UI) Design. . . . . . . . . . . . . . . . 33Using the Code . . . . . . . . . . . . . . . . . . . . . . . . . . 35Application Setup . . . . . . . . . . . . . . . . . . . . . . . . . 40Codes All Together . . . . . . . . . . . . . . . . . . . . . . . . . 44RzStdManage.java . . . . . . . . . . . . . . . . . . . . . . . . . 44mani.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47string.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

[email protected] Free To Ask Question You May Have

Android

Rz RaselChapter - 05Page - 32

Page 33: Android sqlite database by rz rasel 1st edition

Introduction

Here, I have attempted to demonstrate the use of SQLite database in Android in the simplest manner possible. And I try to shows how to perform basic DML and query operations on an SQLite table in Android.

Application background

The example application which I have created is a simple Student Management System, which allows a user to add, delete, modify and view (CRuD) student details. The application ac-cepts a student’s roll number, name and marks and add these details to a student table. For simplicity, I have created all fields of VARCHAR data type, which is a variable length char-acter string.

std_name VARCHAR(255)std_roll INT(3)std_marks INT(3)

Table: std_info

Application user Interface (uI) Design

Android

Rz RaselChapter - 05Page - 33

Page 34: Android sqlite database by rz rasel 1st edition

13:17

Add

Show

Edit

Show All

Delete

Info

Student Name:

Student Roll No:

Exam Marks:

Studen Info Entry

Android

Rz RaselChapter - 05Page - 34

Page 35: Android sqlite database by rz rasel 1st edition

13:17Studen Details

Name: Rz RaselRoll no: 13Marks: 99

Name: JsonRoll no: 2Marks: 90

Name: PallRoll no: 12Marks: 70

Name: Dew DropRoll no: 17Marks: 82

Name: Ravi KrishnaRoll no: 3Marks: 89

Name: Watson

using the Code

The SQLiteDatabase class from the android.database.sqlite package and the Cursor class from the android.database package provide all the functionality required for performing Data Manipulation Language (DML) and query operations on an SQLite table.

The following code shows how to create an SQLite database and a table in the database.

db=openOrCreateDatabase(“StudentDB”, Context.MODE_PRIVATE, null);db.execSQL(“CREATE TABLE IF NOT EXISTS student(rollno VARCHAR, name VARCHAR, marks VARCHAR);”);

In the above code, the openOrCreateDatabase() function is used to open the StudentDB

Android

Rz RaselChapter - 05Page - 35

Page 36: Android sqlite database by rz rasel 1st edition

database if it exists or create a new one if it does not exist. The first parameter of this function specifies the name of the database to be opened or created. The second parameter, Context.MODE_PRIVATE indicates that the database file can only be accessed by the calling appli-cation or all applications sharing the same user ID. The third parameter is a Cursor factory object which can be left null if not required.

The db.execSQL() function executes any SQL command. Here it is used to create the student table if it does not already exist in the database.

Following is the full code of the onCreate() method of the main activity.

public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); // Initializing controls editRollno=(EditText)findViewById(R.id.editRollno); editName=(EditText)findViewById(R.id.editName); editMarks=(EditText)findViewById(R.id.editMarks); btnAdd=(Button)findViewById(R.id.btnAdd); btnDelete=(Button)findViewById(R.id.btnDelete); btnModify=(Button)findViewById(R.id.btnModify); btnView=(Button)findViewById(R.id.btnView); btnViewAll=(Button)findViewById(R.id.btnViewAll); btnShowInfo=(Button)findViewById(R.id.btnShowInfo); // Registering event handlers btnAdd.setOnClickListener(this); btnDelete.setOnClickListener(this); btnModify.setOnClickListener(this); btnView.setOnClickListener(this); btnViewAll.setOnClickListener(this); btnShowInfo.setOnClickListener(this); // Creating database and table db=openOrCreateDatabase(“StudentDB”, Context.MODE_PRIVATE, null); db.execSQL(“CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks VARCHAR);”);}

In the onClick() event handler, we can write the code required to add, delete, modify and view records.

The following code uses the db.execSQL() function to insert a student record in the student table.

db.execSQL(“INSERT INTO student VALUES(‘”+editRollno.getText()+”’,’”+ editName.getText()+”’,’”+editMarks.getText()+”’);”);

The above code generates an INSERT statement by appending the contents of the editable fields into a string and executes the INSERT statement.

In the same way, the DELETE command can be executed as follows:

Android

Rz RaselChapter - 05Page - 36

Page 37: Android sqlite database by rz rasel 1st edition

db.execSQL(“DELETE FROM student WHERE rollno=’”+editRollno.getText()+”’”);

The above code deletes the record of the student whose roll number is entered in the editable field.

The uPDATE command can be executed as follows:

db.execSQL(“UPDATE student SET name=’”+editName.getText()+”’,marks=’”+ editMarks.getText()+”’ WHERE rollno=’”+editRollno.getText()+”’”);

The above code updates the record of the student whose roll number is entered in the editable field.

To view a student record, we execute a query using the rawQuery() method of the SQLite-Database class as follows:

Cursor c=db.rawQuery(“SELECT * FROM student WHERE rollno=’”+editRollno.getText()+”’”, null);if(c.moveToFirst()){ editName.setText(c.getString(1)); editMarks.setText(c.getString(2));}

The above code uses the rawQuery() method of the SQLiteDatabase class to execute the SELECT statement to select the record of the student, whose roll number is specified. It then checks if the record is found using the moveToFirst() method of the Cursor class and dis-plays the name and marks in the respective editable fields.

To view all records, the following code can be used:

Cursor c=db.rawQuery(“SELECT * FROM student”, null);if(c.getCount()==0){ showMessage(“Error”, “No records found”); return;}StringBuffer buffer=new StringBuffer();while(c.moveToNext()){ buffer.append(“Rollno: “+c.getString(0)+”\n”); buffer.append(“Name: “+c.getString(1)+”\n”); buffer.append(“Marks: “+c.getString(2)+”\n\n”);}showMessage(“Student Details”, buffer.toString());

The above code executes the SELECT command to retrieve records of all students and ap-pends them into a string buffer. Finally, it displays the student details using the user-defined showMessage() function.

Following is the full code of the onClick() event handler:

public void onClick(View view){

Android

Rz RaselChapter - 05Page - 37

Page 38: Android sqlite database by rz rasel 1st edition

// Adding a record if(view==btnAdd) { // Checking empty fields if(editRollno.getText().toString().trim().length()==0 || editName.getText().toString().trim().length()==0 || editMarks.getText().toString().trim().length()==0) { showMessage(“Error”, “Please enter all values”); return; } // Inserting record db.execSQL(“INSERT INTO student VALUES(‘”+editRollno.getText()+”’,’”+editName.get-Text()+ “’,’”+editMarks.getText()+”’);”); showMessage(“Success”, “Record added”); clearText(); } // Deleting a record if(view==btnDelete) { // Checking empty roll number if(editRollno.getText().toString().trim().length()==0) { showMessage(“Error”, “Please enter Rollno”); return; } // Searching roll number Cursor c=db.rawQuery(“SELECT * FROM student WHERE rollno=’”+editRollno.getText()+”’”, null); if(c.moveToFirst()) { // Deleting record if found db.execSQL(“DELETE FROM student WHERE rollno=’”+editRollno.getText()+”’”); showMessage(“Success”, “Record Deleted”); } else { showMessage(“Error”, “Invalid Rollno”); } clearText(); } // Modifying a record if(view==btnModify) { // Checking empty roll number if(editRollno.getText().toString().trim().length()==0) { showMessage(“Error”, “Please enter Rollno”); return; } // Searching roll number Cursor c=db.rawQuery(“SELECT * FROM student WHERE rollno=’”+editRollno.getText()+”’”, null);

Android

Rz RaselChapter - 05Page - 38

Page 39: Android sqlite database by rz rasel 1st edition

if(c.moveToFirst()) { // Modifying record if found db.execSQL(“UPDATE student SET name=’”+editName.getText()+”’,marks=’”+editMarks.get-Text()+ “’ WHERE rollno=’”+editRollno.getText()+”’”); showMessage(“Success”, “Record Modified”); } else { showMessage(“Error”, “Invalid Rollno”); } clearText(); } // Viewing a record if(view==btnView) { // Checking empty roll number if(editRollno.getText().toString().trim().length()==0) { showMessage(“Error”, “Please enter Rollno”); return; } // Searching roll number Cursor c=db.rawQuery(“SELECT * FROM student WHERE rollno=’”+editRollno.getText()+”’”, null); if(c.moveToFirst()) { // Displaying record if found editName.setText(c.getString(1)); editMarks.setText(c.getString(2)); } else { showMessage(“Error”, “Invalid Rollno”); clearText(); } } // Viewing all records if(view==btnViewAll) { // Retrieving all records Cursor c=db.rawQuery(“SELECT * FROM student”, null); // Checking if no records found if(c.getCount()==0) { showMessage(“Error”, “No records found”); return; } // Appending records to a string buffer StringBuffer buffer=new StringBuffer(); while(c.moveToNext()) { buffer.append(“Rollno: “+c.getString(0)+”\n”);

Android

Rz RaselChapter - 05Page - 39

Page 40: Android sqlite database by rz rasel 1st edition

buffer.append(“Name: “+c.getString(1)+”\n”); buffer.append(“Marks: “+c.getString(2)+”\n\n”); } // Displaying all records showMessage(“Student Details”, buffer.toString()); } // Displaying info if(view==btnShowInfo) { showMessage(“Student Management Application”, “Developed By Rz Rasel”); }}

The following user-defined function is used to display message to the user:

public void showMessage(String title,String message){ Builder builder=new Builder(this); builder.setCancelable(true); builder.setTitle(title); builder.setMessage(message); builder.show();}

The following user-defined function is used to clear edit fields:

public void clearText(){ editRollno.setText(“”); editName.setText(“”); editMarks.setText(“”); editRollno.requestFocus();}

I hope that it will be helpful for you to the Android platform to understand developing database applications before starting to write more complex applications.

Application Setup

File » New » Android Application Project

Android

Rz RaselChapter - 05Page - 40

Page 41: Android sqlite database by rz rasel 1st edition

CancelFinishNext >< Back?

API 8: Android 2.2 (Froyo)

API 18

API 19: Android 4.4.2

Holo Light with Dark Action Bar

iPackage Name

iMinimum Required SDK:

iTarget SDK:

iCompile With:

iTheme

StudentManagementSystem

rz.rasel.studentmanagementsystem

iProject Name

Student Management SystemiApplication Name

Creates a new Android Application

New Android Application

New Android Application

Android

Rz RaselChapter - 05Page - 41

Page 42: Android sqlite database by rz rasel 1st edition

?

E:\android\rzapp\StudentManagementSystem

Configure Project

New Android Application

New Android Application

Create custom launcher icon

Create activity

Mark this project as a library

Add project to working sets

Create Project in Workspace

Working sets

Next...

Browse...Location:

Working sets:

CancelFinishNext >< Back

Android

Rz RaselChapter - 05Page - 42

Page 43: Android sqlite database by rz rasel 1st edition

CancelFinishNext >< Back?

Creates a new blank activity, with an action bar and optional navigational elements such as tabs or horizontal swipw.

Blank Activity

Select whether to create an activity, and if so, what kind of activity.

Create Activity

New Android Application

Create Activity

Blank ActivityFullscreen ActivityMaster/Detail Flow

Android

Rz RaselChapter - 05Page - 43

Page 44: Android sqlite database by rz rasel 1st edition

CancelFinishNext >< Back?

The type of navigation to use for the activity

NoneiNavigation Type

activity_manageiLayout Name

RzStdManageiActivity Name

Creates a new blank activity, with an action bar and optional navigational elements such as tabs or horizontal swipe.

Blank Activity

New Android Application

Codes All Together

RzStdManage.java

package rz.rasel; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;

Android

Rz RaselChapter - 05Page - 44

Page 45: Android sqlite database by rz rasel 1st edition

import android.widget.EditText; public class RzStdManage extends Activity implements OnClickListener{ EditText editRollno,editName,editMarks; Button btnAdd,btnDelete,btnModify,btnView,btnViewAll,btnShowInfo; SQLiteDatabase db; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); editRollno=(EditText)findViewById(R.id.editRollno); editName=(EditText)findViewById(R.id.editName); editMarks=(EditText)findViewById(R.id.editMarks); btnAdd=(Button)findViewById(R.id.btnAdd); btnDelete=(Button)findViewById(R.id.btnDelete); btnModify=(Button)findViewById(R.id.btnModify); btnView=(Button)findViewById(R.id.btnView); btnViewAll=(Button)findViewById(R.id.btnViewAll); btnShowInfo=(Button)findViewById(R.id.btnShowInfo); btnAdd.setOnClickListener(this); btnDelete.setOnClickListener(this); btnModify.setOnClickListener(this); btnView.setOnClickListener(this); btnViewAll.setOnClickListener(this); btnShowInfo.setOnClickListener(this); db=openOrCreateDatabase(“StudentDB”, Context.MODE_PRIVATE, null); db.execSQL(“CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks VARCHAR);”); } public void onClick(View view) { if(view==btnAdd) { if(editRollno.getText().toString().trim().length()==0 || editName.getText().toString().trim().length()==0 || editMarks.getText().toString().trim().length()==0) { showMessage(“Error”, “Please enter all values”); return; } db.execSQL(“INSERT INTO student VALUES(‘”+editRollno.getText()+”’,’”+editName.getText()+ “’,’”+editMarks.getText()+”’);”); showMessage(“Success”, “Record added”); clearText(); } if(view==btnDelete) { if(editRollno.getText().toString().trim().length()==0) { showMessage(“Error”, “Please enter Rollno”);

Android

Rz RaselChapter - 05Page - 45

Page 46: Android sqlite database by rz rasel 1st edition

return; } Cursor c=db.rawQuery(“SELECT * FROM student WHERE rollno=’”+editRollno.getText()+”’”, null); if(c.moveToFirst()) { db.execSQL(“DELETE FROM student WHERE rollno=’”+editRollno.get-Text()+”’”); showMessage(“Success”, “Record Deleted”); } else { showMessage(“Error”, “Invalid Rollno”); } clearText(); } if(view==btnModify) { if(editRollno.getText().toString().trim().length()==0) { showMessage(“Error”, “Please enter Rollno”); return; } Cursor c=db.rawQuery(“SELECT * FROM student WHERE rollno=’”+editRollno.getText()+”’”, null); if(c.moveToFirst()) { db.execSQL(“UPDATE student SET name=’”+editName.getText()+”’,marks=’”+editMarks.getText()+ “’ WHERE rollno=’”+editRollno.getText()+”’”); showMessage(“Success”, “Record Modified”); } else { showMessage(“Error”, “Invalid Rollno”); } clearText(); } if(view==btnView) { if(editRollno.getText().toString().trim().length()==0) { showMessage(“Error”, “Please enter Rollno”); return; } Cursor c=db.rawQuery(“SELECT * FROM student WHERE rollno=’”+editRollno.getText()+”’”, null); if(c.moveToFirst()) { editName.setText(c.getString(1)); editMarks.setText(c.getString(2)); } else {

Android

Rz RaselChapter - 05Page - 46

Page 47: Android sqlite database by rz rasel 1st edition

showMessage(“Error”, “Invalid Rollno”); clearText(); } } if(view==btnViewAll) { Cursor c=db.rawQuery(“SELECT * FROM student”, null); if(c.getCount()==0) { showMessage(“Error”, “No records found”); return; } StringBuffer buffer=new StringBuffer(); while(c.moveToNext()) { buffer.append(“Rollno: “+c.getString(0)+”\n”); buffer.append(“Name: “+c.getString(1)+”\n”); buffer.append(“Marks: “+c.getString(2)+”\n\n”); } showMessage(“Student Details”, buffer.toString()); } if(view==btnShowInfo) { showMessage(“Student Management Application”, “Developed By Rz Rasel”); } } public void showMessage(String title,String message) { Builder builder=new Builder(this); builder.setCancelable(true); builder.setTitle(title); builder.setMessage(message); builder.show(); } public void clearText() { editRollno.setText(“”); editName.setText(“”); editMarks.setText(“”); editRollno.requestFocus(); }}

mani.xml

<?xml version=”1.0” encoding=”utf-8”?><AbsoluteLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:id=”@+id/myLayout” android:stretchColumns=”0” android:layout_width=”fill_parent” android:layout_height=”fill_parent”> <TextView android:text=”@string/title” android:layout_x=”110dp” android:layout_y=”10dp”

Android

Rz RaselChapter - 05Page - 47

Page 48: Android sqlite database by rz rasel 1st edition

android:layout_width=”wrap_content” android:layout_height=”wrap_content”/> <TextView android:text=”@string/roll_no” android:layout_x=”30dp” android:layout_y=”50dp” android:layout_width=”wrap_content” android:layout_height=”wrap_content”/> <EditText android:id=”@+id/editRollno” android:inputType=”number” android:layout_x=”150dp” android:layout_y=”50dp” android:layout_width=”150dp” android:layout_height=”40dp”/> <TextView android:text=”@string/name” android:layout_x=”30dp” android:layout_y=”100dp” android:layout_width=”wrap_content” android:layout_height=”wrap_content”/> <EditText android:id=”@+id/editName” android:inputType=”text” android:layout_x=”150dp” android:layout_y=”100dp” android:layout_width=”150dp” android:layout_height=”40dp”/> <TextView android:text=”@string/marks” android:layout_x=”30dp” android:layout_y=”150dp” android:layout_width=”wrap_content” android:layout_height=”wrap_content”/> <EditText android:id=”@+id/editMarks” android:inputType=”number” android:layout_x=”150dp” android:layout_y=”150dp” android:layout_width=”150dp” android:layout_height=”40dp”/> <Button android:id=”@+id/btnAdd” android:text=”@string/add” android:layout_x=”30dp” android:layout_y=”200dp” android:layout_width=”100dp” android:layout_height=”40dp”/> <Button android:id=”@+id/btnEdit” android:text=”@string/edit” android:layout_x=”150dp” android:layout_y=”200dp” android:layout_width=”100dp” android:layout_height=”40dp”/> <Button android:id=”@+id/btnDelete” android:text=”@string/delete” android:layout_x=”30dp” android:layout_y=”250dp” android:layout_width=”100dp” android:layout_height=”40dp”/> <Button android:id=”@+id/btnShow”

Android

Rz RaselChapter - 05Page - 48

Page 49: Android sqlite database by rz rasel 1st edition

android:text=”@string/show” android:layout_x=”150dp” android:layout_y=”250dp” android:layout_width=”100dp” android:layout_height=”40dp”/> <Button android:id=”@+id/btnViewAll” android:text=”@string/show_all” android:layout_x=”30dp” android:layout_y=”300dp” android:layout_width=”100dp” android:layout_height=”40dp”/> <Button android:id=”@+id/btnShowInfo” android:text=”@string/info” android:layout_x=”150dp” android:layout_y=”300dp” android:layout_width=”100dp” android:layout_height=”40dp”/> </AbsoluteLayout>

string.xml

<?xml version=”1.0” encoding=”utf-8”?> <resources> <string name=”app_name”>Student Management</string> <string name=”title”>Student Info Entry</string> <string name=”name”>Student Name: </string> <string name=”roll_no”>Student Roll no: </string> <string name=”marks”>Exam Marks: </string> <string name=”add”>Add</string> <string name=”edit”>Edit</string> <string name=”delete”>Delete</string> <string name=”show”>Show</string> <string name=”show_all”>Show All</string> <string name=”info”>Information</string> </resources>

[email protected] YOu’VE GOT SuGGESTIONS FOR IMPROVEMENTS I’D LOVE TO SEE. DON’T HESI-

TATE.IF IT’S HELP YOu PLEASE LEAVE A COMMENT AND LET ME KNOW. I’D LOVE TO

HEAR.FEEL FREE TO SEND MORE FEEDbACK OR QuESTION YOu MAY HAVE.

������������z������������

Android

Rz RaselChapter - 05Page - 49