Sunteți pe pagina 1din 49

Dinner Time Hand Note

Android
Rz Rasel

Android

Dinner Time Hand Note


Android
Rz Rasel

Rz Rasel

Android

Dinner Time Hand Note


Android

DESIGN AND DEVELOPMENT

1st Edition

Rz Rasel

Rz Rasel

Android

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 mechanical 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.
rzandapp@gmail.com

1st Edition: August 2014

Cover Illustration Copyright by Rz Rasel (rzandapp@gmail.com)


Cover design by Rz Rasel.
Book design by Rz Rasel
Editing by Rz Rasel
Chapter opening illustrations Rz Rasel

Rz Rasel

Android

REDITS

I would like to thanks all of them.


Author
Rz 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:- rzandapp@gmail.com.

I would like to thanks all of them.

Rz Rasel

Android

bout author

Rz Rasel (Rashed - Uz - Zaman) Software Engineer. Software developer, Software designer,


System designer, Database designer, Web developer, Web designer, and blogger born in Bangladesh, 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.wordpress.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://arzrasel.wordpress.com or e-mail him at rzandapp@gmail.com.

Rz Rasel

Rz Rasel

Android

uthors Note

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, clarifications, 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 (thats what I call wishful thinking).

Rz Rasel

Rz Rasel

Android

et In Touch

Get in touch with writer


WordPress Blog:- https://arzrasel.wordpress.com
Facebook:-
https://www.facebook.com/rzprogramming
Facebook:-
https://www.facebook.com/groups/merzrasel/
Facebook:-
https://www.facebook.com/groups/rzprogrammer/
E-mail:- rzandapp@gmail.com

Rz Rasel

Rz Rasel

Android

ontents

01
02
03

04

SQLite and Relational Database


What is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Features of SQLite. . . . . . . . . . . . . . . . . . . . . . . . . 15
Advantages of using SQLite. . . . . . . . . . . . . . . . . . . . . 15
Getting started with SQLite Database
What is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . .
Getting Started with SQLite. . . . . . . . . . . . . . . . . . . . .
SQLite Java Classes. . . . . . . . . . . . . . . . . . . . . . . . .
Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
SQLite Database. . . . . . . . . . . . . . . . . . . . . . . . . .
SQLite Open Helper . . . . . . . . . . . . . . . . . . . . . . . . .

18
18
19
19
19
19

SQLite Database for Android Developers


Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . .
What is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . .
A Quick Review of Database Fundamentals . . . . . . . . . . . . . .
The Chess Tournament Database . . . . . . . . . . . . . . . . . .
Designing the Database Schema. . . . . . . . . . . . . . . . . . .
Working with Tables . . . . . . . . . . . . . . . . . . . . . . . .
Populating Tables with Data Records . . . . . . . . . . . . . . . . .
Querying Tables for Results with SELECT . . . . . . . . . . . . . . .
Using Column Aliases and Calculated Columns. . . . . . . . . . . .
Altering Data in Tables. . . . . . . . . . . . . . . . . . . . . . .
Using Foreign Keys and Composite Keys. . . . . . . . . . . . . . .
Querying Across Multiple Tables Using JOIN . . . . . . . . . . . . .
Executing More Complex Queries . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

21
21
21
22
22
22
23
24
24
24
25
26
26
27

SQLite database CRUD operations


What is Sqlite in Android? . . . . . . . . . . . . . . . . . . . . . .
Quick explanation of the API classes and methods involved. . . . . .
SQLiteDatabase . . . . . . . . . . . . . . . . . . . . . . . . . .
execSQL(). . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29
29
29
29

Rz Rasel

Android

ontents

05

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

29
29
29
30
30
30
30
31
31
31

Android SQLite Database and CRUD Operation


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Application Background . . . . . . . . . . . . . . . . . . . . . . .
Application User Interface (UI) Design. . . . . . . . . . . . . . . .
Using the Code . . . . . . . . . . . . . . . . . . . . . . . . . . .
Application Setup . . . . . . . . . . . . . . . . . . . . . . . . . .
Codes All Together. . . . . . . . . . . . . . . . . . . . . . . . .
RzStdManage.java. . . . . . . . . . . . . . . . . . . . . . . . .
mani.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
string.xml. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

33
33
33
35
40
44
44
47
49

rzandapp@gmail.com
Feel Free To Ask Question You May Have

Rz Rasel

Android

Rz Rasel

Android

Rz Rasel

Android

Rz Rasel

Android

ontents

01

SQLite and Relational Database


What is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Features of SQLite. . . . . . . . . . . . . . . . . . . . . . . . . 15
Advantages of using SQLite. . . . . . . . . . . . . . . . . . . . . 15
rzandapp@gmail.com
Feel Free To Ask Question You May Have

Chapter - 01
Page - 14

Rz Rasel

Android
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 memory 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 columns 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
Zero configuration SQLite does not need to be Installed as there is no setup procedure 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-Platform Database 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.
Single Database File An SQLite database is a single ordinary disk file that can be located 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.
Chapter - 01
Page - 15

Rz Rasel

Android
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 bigand 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 consumption are reduced.
Small edits only overwrite the parts of the file that change, not the entire file, thus improving 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 redesigning, rewriting, and retesting application code.
rzandapp@gmail.com
If youve got suggestions for improvements Id love to see. Dont hesitate.
IF ITS HELP YOU PLEASE LEAVE A COMMENT AND LET ME KNOW. ID LOVE TO
HEAR.
Feel Free To Send More Feedback Or Question You May Have.
z

Chapter - 01
Page - 16

Rz Rasel

Android

ontents

02

Getting started with SQLite Database


What is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . .
Getting Started with SQLite. . . . . . . . . . . . . . . . . . . . .
SQLite Java Classes. . . . . . . . . . . . . . . . . . . . . . . . .
Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
SQLite Database. . . . . . . . . . . . . . . . . . . . . . . . . .
SQLite Open Helper . . . . . . . . . . . . . . . . . . . . . . . . .

18
18
19
19
19
19

rzandapp@gmail.com
Feel Free To Ask Question You May Have

Chapter - 02
Page - 17

Rz Rasel

Android
If youre just getting started as an Android app developer, it wont 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
users 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 implementation 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 library. This is great news while youre learning to use SQLite because it makes it much easier
to manipulate even large databases when compared to more conventional database solutions.
In case youre 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 youre 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 structured 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
Chapter - 02
Page - 18

Rz Rasel

Android
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 management 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 database. 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 understand than conventional RDBMS interfaces and because SQLite is so lightweight, even if
your code isnt perfect you shouldnt 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.
rzandapp@gmail.com
If youve got suggestions for improvements Id love to see. Dont hesitate.
IF ITS HELP YOU PLEASE LEAVE A COMMENT AND LET ME KNOW. ID LOVE TO
HEAR.
Feel Free To Send More Feedback Or Question You May Have.
z

Chapter - 02
Page - 19

Rz Rasel

Android

ontents

03

SQLite Database for Android Developers


Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . .
What is SQLite? . . . . . . . . . . . . . . . . . . . . . . . . . .
A Quick Review of Database Fundamentals . . . . . . . . . . . . . .
The Chess Tournament Database . . . . . . . . . . . . . . . . . .
Designing the Database Schema. . . . . . . . . . . . . . . . . . .
Working with Tables . . . . . . . . . . . . . . . . . . . . . . . .
Populating Tables with Data Records . . . . . . . . . . . . . . . . .
Querying Tables for Results with SELECT . . . . . . . . . . . . . . .
Using Column Aliases and Calculated Columns. . . . . . . . . . . .
Altering Data in Tables. . . . . . . . . . . . . . . . . . . . . . .
Using Foreign Keys and Composite Keys. . . . . . . . . . . . . . .
Querying Across Multiple Tables Using JOIN . . . . . . . . . . . . .
Executing More Complex Queries . . . . . . . . . . . . . . . . . .
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

21
21
21
22
22
22
23
24
24
24
25
26
26
27

rzandapp@gmail.com
Feel Free To Ask Question You May Have

Chapter - 03
Page - 20

Rz Rasel

Android
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 database 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 database-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 using 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; its more a theoretical exercise.
However, if you are planning to develop Android applications which rely upon SQLite databases, 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 youre familiar with SQL, then SQLite will be very easy to pick up. SQLite is basically a stripped-down SQL database engine for embedded devices. For specific information
about SQLite and its features, functionality, and limitations, see the SQLite online documentation (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 spreadsheet. For an object oriented programming perspective, each table in a database often represents 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.
Lets look at a quick example. Lets say you have a company database with a table called Employee. 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)

Chapter - 03
Page - 21

Rz Rasel

Android
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 lets do so. Lets 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 players overall tournament score is calculated 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 0100.
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 players 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 youve determined which columns are necessary for each table, youre ready to create
some tables within your database schema.
Working with Tables
Lets begin by creating the Players table. This table requires a unique player id to reference
Chapter - 03
Page - 22

Rz Rasel

Android
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 towards the players final tournament score (as a percentage). Heres 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, lets 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 were add it, well 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 players 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:

Chapter - 03
Page - 23

Rz Rasel

Android
INSERT into games (gamename, weight) VALUES
(Final, .35);
Querying Tables for Results with SELECT
How do we know the data weve added is in the table? Well, thats 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
-- ------------
1 Semi-Final
2
Warm-up Heat 1
3
Warm-up Heat 2
4
Warm-up Heat 3
5
Warm-up Heat 4
6 Final

weight
------0.25
0.1
0.1
0.1
0.1
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: Its the players first and last names concatenated 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
1
Avishek Ahhmed
2
Garry Kasparov
3
Parvez Rashid
4
Altering Data in Tables
Avisheks (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 players
SET 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:

Chapter - 03
Page - 24

Rz Rasel

Android
DELETE FROM players;
Using Foreign Keys and Composite Keys
Now that we have our Players and Games all set up, lets 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 its time to insert some data to the Game Results table. Lets 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 lets assume the tournament is played and the scores are added to the Game Results table. 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 82
1 2 88
1 3 78
1 4 90
1 5 85
1 6 94
2 1 10
2 2 60
2 3 50
2 4 55
2 5 45
2 6 65

Chapter - 03
Page - 25

Rz Rasel

Android
3 6 100
3 5 100
3 4 100
3 3 100
3 2 100
3 1 100
As you can see, this listing is not particularly human-readable.
Querying Across Multiple Tables Using JOIN
Wouldnt 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.
Lets 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):
SELECT
players.fname|| || players.lname AS PlayerName, games.gamename, game_results.score
FROM game_results
JOIN 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
------------------
Rz Rasel
Avishek Ahmed
Garry Kasparov

gamename score
-------------- ----Final
94
Final
65
Final
100

Executing More Complex Queries


The skys 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:
SELECT
players.fname|| || players.lname AS PlayerName,
SUM((games.weight * game_results.score)) AS TotalWeightedScore
FROM game_results
JOIN players ON (players.id = game_results.playerid)
JOIN games ON (games.id = game_results.gameid)
GROUP BY game_results.playerid
ORDER BY TotalWeightedScore DESC;
This query gathers information from several different tables using JOINs and calculates the
tournament results in a readable way. So lets look at what this query does:

Chapter - 03
Page - 26

Rz Rasel

Android
Each players full name is displayed as the first result column (calculated from their first
and last name)
Each players 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.0
Rz Rasel
87.5
Avishek Ahmed
46.25
Conclusion
This concludes our exploration of a simple SQLite database example: a chess tournament database. Hopefully youve reacquainted yourself with relational database concepts like tables,
records, and queries and familiarized yourself with many of the commonly used SQLite commands. Finally, youve walked through the design and usage of an example database. Now
that youve got a handle on how SQLite databases work, youre ready to use them within your
Android applications.
rzandapp@gmail.com
If youve got suggestions for improvements Id love to see. Dont hesitate.
IF ITS HELP YOU PLEASE LEAVE A COMMENT AND LET ME KNOW. ID LOVE TO
HEAR.
Feel Free To Send More Feedback Or Question You May Have.
z

Chapter - 03
Page - 27

Rz Rasel

Android

ontents

04

SQLite database CRUD operations


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

29
29
29
29
29
29
29
30
30
30
30
31
31
31

rzandapp@gmail.com
Feel Free To Ask Question You May Have

Chapter - 04
Page - 28

Rz Rasel

Android
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. Normal 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 commands, and perform other common database management tasks. Here we are using execSQL() 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 returns Cursor.
SQLiteOpenHelper
For adding SQLite database connectivity in android, we need to create a separate class for database. 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);
Chapter - 04
Page - 29

Rz Rasel

Android
}
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 contains 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 example it is 13.
Chapter - 04
Page - 30

Rz Rasel

Android
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 operation 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.
rzandapp@gmail.com
If youve got suggestions for improvements Id love to see. Dont hesitate.
IF ITS HELP YOU PLEASE LEAVE A COMMENT AND LET ME KNOW. ID LOVE TO
HEAR.
Feel Free To Send More Feedback Or Question You May Have.
z

Chapter - 04
Page - 31

Rz Rasel

Android

ontents

05

Android SQLite Database and CRUD Operation


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Application Background . . . . . . . . . . . . . . . . . . . . . . .
Application User Interface (UI) Design. . . . . . . . . . . . . . . .
Using the Code . . . . . . . . . . . . . . . . . . . . . . . . . . .
Application Setup . . . . . . . . . . . . . . . . . . . . . . . . . .
Codes All Together. . . . . . . . . . . . . . . . . . . . . . . . .
RzStdManage.java. . . . . . . . . . . . . . . . . . . . . . . . .
mani.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
string.xml. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

33
33
33
35
40
44
44
47
49

rzandapp@gmail.com
Feel Free To Ask Question You May Have

Chapter - 05
Page - 32

Rz Rasel

Android
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 accepts a students 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 character string.

Table: std_info
std_name VARCHAR(255)
std_roll INT(3)
std_marks INT(3)
Application User Interface (UI) Design

Chapter - 05
Page - 33

Rz Rasel

Android

13:17
Studen Info Entry

Student Name:
Student Roll No:
Exam Marks:

Add

Edit

Delete

Show

Show All

Info

Chapter - 05
Page - 34

Rz Rasel

Android

13:17
Studen Details

Name:
Rz Rasel
Roll no:
13
Marks: 99
Name: Json
Roll no:
2
Marks: 90
Name: Pall
Roll no:
12
Marks: 70
Name:
Dew Drop
Roll no:
17
Marks: 82
Name:
Ravi Krishna
Roll no:
3
Marks: 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

Chapter - 05
Page - 35

Rz Rasel

Android
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 application 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:

Chapter - 05
Page - 36

Rz Rasel

Android
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 SQLiteDatabase 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 displays 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 appends 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)
{

Chapter - 05
Page - 37

Rz Rasel

Android
// 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.getText()+
,+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);

Chapter - 05
Page - 38

Rz Rasel

Android
if(c.moveToFirst())
{
// Modifying record if found
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();
}
// 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);

Chapter - 05
Page - 39

Rz Rasel

Android
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

Chapter - 05
Page - 40

Rz Rasel

Android
New Android Application
New Android Application
Creates a new Android Application

Application Name

Student Management System

Project Name

StudentManagementSystem

Package Name

rz.rasel.studentmanagementsystem

Minimum Required SDK:

API 8: Android 2.2 (Froyo)

Target SDK:

API 18

Compile With:

API 19: Android 4.4.2

Theme

Holo Light with Dark Action Bar

< Back

Next >

Finish

Cancel

Chapter - 05
Page - 41

Rz Rasel

Android
New Android Application
New Android Application
Configure Project
Create custom launcher icon
Create activity
Mark this project as a library
Create Project in Workspace
Location:

Browse...

E:\android\rzapp\StudentManagementSystem

Working sets
Add project to working sets
Working sets:

Next...

< Back

Next >

Finish

Cancel

Chapter - 05
Page - 42

Rz Rasel

Android
New Android Application
Create Activity
Select whether to create an activity, and if so, what kind of activity.
Create Activity
Blank Activity
Fullscreen Activity
Master/Detail Flow

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

< Back

Next >

Finish

Cancel

Chapter - 05
Page - 43

Rz Rasel

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

Activity Name

RzStdManage

Layout Name

activity_manage

Navigation Type

None

The type of navigation to use for the activity

< Back

Next >

Finish

Cancel

Codes All Together


RzStdManage.java
package rz.rasel;
import
import
import
import
import
import
import
import
import

android.app.Activity;
android.app.AlertDialog.Builder;
android.content.Context;
android.database.Cursor;
android.database.sqlite.SQLiteDatabase;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
Chapter - 05
Page - 44

Rz Rasel

Android
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);

Chapter - 05
Page - 45

Rz Rasel

Android
return;
}
Cursor c=db.rawQuery(SELECT * FROM student WHERE rollno=+editRollno.
getText()+, null);
if(c.moveToFirst())
{
db.execSQL(DELETE FROM student WHERE rollno=+editRollno.getText()+);
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
{

Chapter - 05
Page - 46

Rz Rasel

Android
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

Chapter - 05
Page - 47

Rz Rasel

Android
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

Chapter - 05
Page - 48

Rz Rasel

Android
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>
rzandapp@gmail.com
If youve got suggestions for improvements Id love to see. Dont hesitate.
IF ITS HELP YOU PLEASE LEAVE A COMMENT AND LET ME KNOW. ID LOVE TO
HEAR.
Feel Free To Send More Feedback Or Question You May Have.
z

Chapter - 05
Page - 49

Rz Rasel

S-ar putea să vă placă și