Upload
lyliem
View
236
Download
0
Embed Size (px)
Citation preview
Introduction Most of the applications require the data to be saved and loaded when it is
demanded As we see in games that whole game is saved and later on this is loaded again You
also want to store user preferences so that user may customize application and store data
entered by the user
Android Methods for saving data
Shared Preferences When you want a limited application data such as user preferences related
to application UI you prefer to store data using Shared Preferences In this method you store
data as key values pairs
Files In android you are allowed to create and readwrite to files You can create files on the
internal or external media of the device
SQLite Database Android also facilitates to work with relational database system The
Database system used in android is SQLite Database system
Content Provider Content Providers let you expose a well-defined interface for using and
sharing private data You can control access to Content Providers using the standard permission
system
Here we are going to discuss how SQLite database is used to save data in android Firstly letrsquos
have a brief introduction about SQLite database system
SQLite Database
SQLite database is a
Zero configuration (as it is default database provided embedded in android so no
configuration is required)
Lightweight ( requires minimum memory)
Open source (no license)
Single database file (Only one file is made against one database)
If an application creates a database it is stored in following directory
DATAdataAPP_NAMEdatabasesFILENAME
Before starting to work with database letrsquos discuss essential concepts which can help in
understanding the topic
1 SQL SQL is a structured query language that is used for database manipulation It
provides simple queries to create and manipulate database system Letrsquos start from data
retrieval using SQL
11 Select statement
Select statement is used to get data from database system The syntax of using
select statement is as follow
Select col1col2hellipcoln From TableName where some condition order by column
Eg select rollno from students where name=rsquoAsadrsquo
To get all columns of a table use as select from students
12 Data Definition
121 create table
This statement is used to create a new table if it does not exist The syntax is
as follow
CREATE TABLE newtable(
Col1 INT
Col2 VARCHAR(50)
col3 DATE NOT NULL
PRIMARY KEY (col1 col2)
)
Example create table users (uid int primary key password varchar(50))
122 Drop table
This statement is used to drop a table from database system if it exist
Syntax is as follow
Drop table tablename
Example drop table users
123 Alter table
Alter table statement is used to update table definition
Syntax is as follow
Update table tableName Add columnName type
Example Update table users Add age int
13 Data Manipulation
131 Insert statement
Insert statement is used to add records in database system
Syntax is as follow
Insert into tablename(col1col2hellipcoln) values(v1v2hellipvn)
Example insert into users(uidpassword) values(12rsquoabcd123rsquo)
132 Delete statement
Delet statement is used to delete records in database system
Syntax is as follow
Delete from tablename where somecondition
Example Delete from users where uid=12
Delete from users will delete all records from database
133 update statement
Update statement is used to update records in database system
Syntax is as follow
Update table tableName set col1=v1 where col2=v2
Example Update table users set password=rsquo6t8979rsquo where uid=12
2 Packages to use SQLite Database
Following packages are used to work with SQLite Database system
androiddatabase
androiddatabasesqlite
3 SQLiteopenHelper
To create and upgrade database in our application we need a class that extends
SQLiteOpenHelper class To use it we have to override two abstract methods onCreate()
and onUpgrade() SQLiteOpenHelper provides following methods
onCreat() this method is called when database does not exist
onUpgrade() this method allow you to update or alter database schema
getReadableDatabase() create orand open a database for only data reading
getWriteableDatabase()create orand open a database for both data reading and
writing
close() close the database if it is opened
onOpen() this method is called when a database is opened
4 ContentValues
ContentValues is a data structure used to store key and corresponding values Keys
represent columns in database and values are their values This is helpful for inserting
and updating records in database
5 SQLiteDataBase class
This is base class to work with database system This class has methods to manage
database It provides useful methods to insert a record delete a record and update a
record in a database All manipulation of database is done through this class Some most
commonly used methods of this class are given bellow
insert(String tableName String nullColumnHack ContentValues contentValues)
this method is used to insert a record in a database table
delete(String table String whereClause String[] whereArgs)
this method is used to delete a record from database table
update (String table ContentValues contentValuesString whereClause String[] whereArgs)
this method is used to delete a record from database table
this method is used to select records from database table and return cursor object we
will learn cursor a little bit later
ltExamplerawQuery(select from users where uid = new String[] id )
query(String table String[] columns String selection String[] Args String
groupByClause String havingClause String orderByClause String
NoOfRowsToBeFethed)
this method executes given query and return cursor object
6 Cursor
Cursor is just like ResultSet in java It contains all the records retrieved in form of result
of a query Cursor has number of methods to manipulate returned data Some of them
are as follow
MoveToNext() Move cursor to next record
MoveToPrevious() Move cursor to previous record
MoveToFirst() Move cursor to first record
MoveToLast() Move cursor to last record
MoveToPosition(int p) Move cursor to a record at given position
isFirst() Returns true if it is first record
isLast() Returns true if it is last record
getString(int columnIndex) Return String stored at given column of a row
getInt(int columnIndex) Return integer value stored at given column of a row
getDouble(int columnIndex) Return double value stored at given column of a row
Creating an application that explain working with database
In this example I have made 5 activities first is main activity and a DataBase helper class named
as DBCreator and a student class as Data Transfer Object(DTO) and a DAO class that interact with
database
Letrsquos start with class DBCreater code is given below
package commujadid001
import androidcontentContext
import androiddatabasesqliteSQLiteDatabase
import androiddatabasesqliteSQLiteDatabaseCursorFactory
import androiddatabasesqliteSQLiteOpenHelper
import androidutilLog
public class DBCreator extends SQLiteOpenHelper
constatns to refer database file table name and datbase version
public static final String student_TABLE_NAME = Student
public static final String DATABASE_NAME = studentsResultsdb
private static int DATABASE_VERSION = 1
constructor it only calls super class constructor
public DBCreator(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
TODO Auto-generated constructor stub
onCreat() method is called to create database first time
Override
public void onCreate(SQLiteDatabase db)
sql query to create a table
String sql = CREATE TABLE + student_TABLE_NAME + (studentId INTEGER
PRIMARY KEY AUTOINCREMENT studentName TEXTMarks INTEGER)
Logging a tag for debugging purposes
Logd(DATABASE_NAME oncreate+sql)
executing sql query
dbexecSQL(sql)
onupgrade() method definition
Override
public void onUpgrade(SQLiteDatabase db int oldVersion int newVersion)
sql query to drop an existing table normally here alter table query is written but it is
just an example
dbexecSQL(DROP TABLE IF EXISTS +student_TABLE_NAME + )
Logging a tag for debugging purpose
Logd(DATABASE_NAME onupdate)
now calling onCreate to create table again
onCreate(db)
Explaination
Constructor it is used to create an object of this class and call constructor of super class
onCreate() onCreate() is called by android framework when we call getWritableDatabase() or
getReadableDatbase() methods it is called when database file is not present
onUpgrade() it is called whenever a new version of datbase become available such that definition
of database is changed a new column has been added datatype of a column is changed etc
student Class
package commujadid001 public class student data memebers private int id private String Name public int marks constructors public student(String name int marks) Name = name thismarks = marks public student(int id String name int marks) super() thisid = id Name = name thismarks = marks setters and getters public int getId() return id public void setId(int id) thisid = id
public String getName() return Name public void setName(String name) Name = name public int getMarks() return marks public void setMarks(int marks) thismarks = marks
Explanation student class is self explanatory it has member variables getters setters
construtors
DAO CLASS
package commujadid001
import androidcontentContentValues
import androidcontentContext
import androiddatabaseCursor
import androiddatabasesqliteSQLiteDatabase
import androidutilLog
DAO class
public class DAO
an object of class SQLiteDatabase which have built in functions to manipulate database
SQLiteDatabase db
creating a reference of class DBCreator
DBCreator dbcreator
creating an object of type Context
Context context
constructor
public DAO(Context context)
initializing data members
dbcreator=new DBCreator(context)
getting writable datbase from class DBCreator this method is inherited in
DBCreator from its parent
db=dbcreatorgetWritableDatabase()
method to insert a record
public int InsertRecord(student s)
try
sql query to insert a record
String sql=inser+DBCreatorstudent_TABLE_NAME+(studentNameMarks)
values(+sgetName()++sgetMarks()+ )
executing sql query
dbexecSQL(sql)
return 1
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOInsert)
return -1
method to delete a record
public int DeleteRecord(int id)
try
using built in delete function of class SQLitDatabase
return dbdelete(DBCreatorstudent_TABLE_NAME studentId= new
String[]+id)
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
1 SQL SQL is a structured query language that is used for database manipulation It
provides simple queries to create and manipulate database system Letrsquos start from data
retrieval using SQL
11 Select statement
Select statement is used to get data from database system The syntax of using
select statement is as follow
Select col1col2hellipcoln From TableName where some condition order by column
Eg select rollno from students where name=rsquoAsadrsquo
To get all columns of a table use as select from students
12 Data Definition
121 create table
This statement is used to create a new table if it does not exist The syntax is
as follow
CREATE TABLE newtable(
Col1 INT
Col2 VARCHAR(50)
col3 DATE NOT NULL
PRIMARY KEY (col1 col2)
)
Example create table users (uid int primary key password varchar(50))
122 Drop table
This statement is used to drop a table from database system if it exist
Syntax is as follow
Drop table tablename
Example drop table users
123 Alter table
Alter table statement is used to update table definition
Syntax is as follow
Update table tableName Add columnName type
Example Update table users Add age int
13 Data Manipulation
131 Insert statement
Insert statement is used to add records in database system
Syntax is as follow
Insert into tablename(col1col2hellipcoln) values(v1v2hellipvn)
Example insert into users(uidpassword) values(12rsquoabcd123rsquo)
132 Delete statement
Delet statement is used to delete records in database system
Syntax is as follow
Delete from tablename where somecondition
Example Delete from users where uid=12
Delete from users will delete all records from database
133 update statement
Update statement is used to update records in database system
Syntax is as follow
Update table tableName set col1=v1 where col2=v2
Example Update table users set password=rsquo6t8979rsquo where uid=12
2 Packages to use SQLite Database
Following packages are used to work with SQLite Database system
androiddatabase
androiddatabasesqlite
3 SQLiteopenHelper
To create and upgrade database in our application we need a class that extends
SQLiteOpenHelper class To use it we have to override two abstract methods onCreate()
and onUpgrade() SQLiteOpenHelper provides following methods
onCreat() this method is called when database does not exist
onUpgrade() this method allow you to update or alter database schema
getReadableDatabase() create orand open a database for only data reading
getWriteableDatabase()create orand open a database for both data reading and
writing
close() close the database if it is opened
onOpen() this method is called when a database is opened
4 ContentValues
ContentValues is a data structure used to store key and corresponding values Keys
represent columns in database and values are their values This is helpful for inserting
and updating records in database
5 SQLiteDataBase class
This is base class to work with database system This class has methods to manage
database It provides useful methods to insert a record delete a record and update a
record in a database All manipulation of database is done through this class Some most
commonly used methods of this class are given bellow
insert(String tableName String nullColumnHack ContentValues contentValues)
this method is used to insert a record in a database table
delete(String table String whereClause String[] whereArgs)
this method is used to delete a record from database table
update (String table ContentValues contentValuesString whereClause String[] whereArgs)
this method is used to delete a record from database table
this method is used to select records from database table and return cursor object we
will learn cursor a little bit later
ltExamplerawQuery(select from users where uid = new String[] id )
query(String table String[] columns String selection String[] Args String
groupByClause String havingClause String orderByClause String
NoOfRowsToBeFethed)
this method executes given query and return cursor object
6 Cursor
Cursor is just like ResultSet in java It contains all the records retrieved in form of result
of a query Cursor has number of methods to manipulate returned data Some of them
are as follow
MoveToNext() Move cursor to next record
MoveToPrevious() Move cursor to previous record
MoveToFirst() Move cursor to first record
MoveToLast() Move cursor to last record
MoveToPosition(int p) Move cursor to a record at given position
isFirst() Returns true if it is first record
isLast() Returns true if it is last record
getString(int columnIndex) Return String stored at given column of a row
getInt(int columnIndex) Return integer value stored at given column of a row
getDouble(int columnIndex) Return double value stored at given column of a row
Creating an application that explain working with database
In this example I have made 5 activities first is main activity and a DataBase helper class named
as DBCreator and a student class as Data Transfer Object(DTO) and a DAO class that interact with
database
Letrsquos start with class DBCreater code is given below
package commujadid001
import androidcontentContext
import androiddatabasesqliteSQLiteDatabase
import androiddatabasesqliteSQLiteDatabaseCursorFactory
import androiddatabasesqliteSQLiteOpenHelper
import androidutilLog
public class DBCreator extends SQLiteOpenHelper
constatns to refer database file table name and datbase version
public static final String student_TABLE_NAME = Student
public static final String DATABASE_NAME = studentsResultsdb
private static int DATABASE_VERSION = 1
constructor it only calls super class constructor
public DBCreator(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
TODO Auto-generated constructor stub
onCreat() method is called to create database first time
Override
public void onCreate(SQLiteDatabase db)
sql query to create a table
String sql = CREATE TABLE + student_TABLE_NAME + (studentId INTEGER
PRIMARY KEY AUTOINCREMENT studentName TEXTMarks INTEGER)
Logging a tag for debugging purposes
Logd(DATABASE_NAME oncreate+sql)
executing sql query
dbexecSQL(sql)
onupgrade() method definition
Override
public void onUpgrade(SQLiteDatabase db int oldVersion int newVersion)
sql query to drop an existing table normally here alter table query is written but it is
just an example
dbexecSQL(DROP TABLE IF EXISTS +student_TABLE_NAME + )
Logging a tag for debugging purpose
Logd(DATABASE_NAME onupdate)
now calling onCreate to create table again
onCreate(db)
Explaination
Constructor it is used to create an object of this class and call constructor of super class
onCreate() onCreate() is called by android framework when we call getWritableDatabase() or
getReadableDatbase() methods it is called when database file is not present
onUpgrade() it is called whenever a new version of datbase become available such that definition
of database is changed a new column has been added datatype of a column is changed etc
student Class
package commujadid001 public class student data memebers private int id private String Name public int marks constructors public student(String name int marks) Name = name thismarks = marks public student(int id String name int marks) super() thisid = id Name = name thismarks = marks setters and getters public int getId() return id public void setId(int id) thisid = id
public String getName() return Name public void setName(String name) Name = name public int getMarks() return marks public void setMarks(int marks) thismarks = marks
Explanation student class is self explanatory it has member variables getters setters
construtors
DAO CLASS
package commujadid001
import androidcontentContentValues
import androidcontentContext
import androiddatabaseCursor
import androiddatabasesqliteSQLiteDatabase
import androidutilLog
DAO class
public class DAO
an object of class SQLiteDatabase which have built in functions to manipulate database
SQLiteDatabase db
creating a reference of class DBCreator
DBCreator dbcreator
creating an object of type Context
Context context
constructor
public DAO(Context context)
initializing data members
dbcreator=new DBCreator(context)
getting writable datbase from class DBCreator this method is inherited in
DBCreator from its parent
db=dbcreatorgetWritableDatabase()
method to insert a record
public int InsertRecord(student s)
try
sql query to insert a record
String sql=inser+DBCreatorstudent_TABLE_NAME+(studentNameMarks)
values(+sgetName()++sgetMarks()+ )
executing sql query
dbexecSQL(sql)
return 1
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOInsert)
return -1
method to delete a record
public int DeleteRecord(int id)
try
using built in delete function of class SQLitDatabase
return dbdelete(DBCreatorstudent_TABLE_NAME studentId= new
String[]+id)
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
Example Delete from users where uid=12
Delete from users will delete all records from database
133 update statement
Update statement is used to update records in database system
Syntax is as follow
Update table tableName set col1=v1 where col2=v2
Example Update table users set password=rsquo6t8979rsquo where uid=12
2 Packages to use SQLite Database
Following packages are used to work with SQLite Database system
androiddatabase
androiddatabasesqlite
3 SQLiteopenHelper
To create and upgrade database in our application we need a class that extends
SQLiteOpenHelper class To use it we have to override two abstract methods onCreate()
and onUpgrade() SQLiteOpenHelper provides following methods
onCreat() this method is called when database does not exist
onUpgrade() this method allow you to update or alter database schema
getReadableDatabase() create orand open a database for only data reading
getWriteableDatabase()create orand open a database for both data reading and
writing
close() close the database if it is opened
onOpen() this method is called when a database is opened
4 ContentValues
ContentValues is a data structure used to store key and corresponding values Keys
represent columns in database and values are their values This is helpful for inserting
and updating records in database
5 SQLiteDataBase class
This is base class to work with database system This class has methods to manage
database It provides useful methods to insert a record delete a record and update a
record in a database All manipulation of database is done through this class Some most
commonly used methods of this class are given bellow
insert(String tableName String nullColumnHack ContentValues contentValues)
this method is used to insert a record in a database table
delete(String table String whereClause String[] whereArgs)
this method is used to delete a record from database table
update (String table ContentValues contentValuesString whereClause String[] whereArgs)
this method is used to delete a record from database table
this method is used to select records from database table and return cursor object we
will learn cursor a little bit later
ltExamplerawQuery(select from users where uid = new String[] id )
query(String table String[] columns String selection String[] Args String
groupByClause String havingClause String orderByClause String
NoOfRowsToBeFethed)
this method executes given query and return cursor object
6 Cursor
Cursor is just like ResultSet in java It contains all the records retrieved in form of result
of a query Cursor has number of methods to manipulate returned data Some of them
are as follow
MoveToNext() Move cursor to next record
MoveToPrevious() Move cursor to previous record
MoveToFirst() Move cursor to first record
MoveToLast() Move cursor to last record
MoveToPosition(int p) Move cursor to a record at given position
isFirst() Returns true if it is first record
isLast() Returns true if it is last record
getString(int columnIndex) Return String stored at given column of a row
getInt(int columnIndex) Return integer value stored at given column of a row
getDouble(int columnIndex) Return double value stored at given column of a row
Creating an application that explain working with database
In this example I have made 5 activities first is main activity and a DataBase helper class named
as DBCreator and a student class as Data Transfer Object(DTO) and a DAO class that interact with
database
Letrsquos start with class DBCreater code is given below
package commujadid001
import androidcontentContext
import androiddatabasesqliteSQLiteDatabase
import androiddatabasesqliteSQLiteDatabaseCursorFactory
import androiddatabasesqliteSQLiteOpenHelper
import androidutilLog
public class DBCreator extends SQLiteOpenHelper
constatns to refer database file table name and datbase version
public static final String student_TABLE_NAME = Student
public static final String DATABASE_NAME = studentsResultsdb
private static int DATABASE_VERSION = 1
constructor it only calls super class constructor
public DBCreator(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
TODO Auto-generated constructor stub
onCreat() method is called to create database first time
Override
public void onCreate(SQLiteDatabase db)
sql query to create a table
String sql = CREATE TABLE + student_TABLE_NAME + (studentId INTEGER
PRIMARY KEY AUTOINCREMENT studentName TEXTMarks INTEGER)
Logging a tag for debugging purposes
Logd(DATABASE_NAME oncreate+sql)
executing sql query
dbexecSQL(sql)
onupgrade() method definition
Override
public void onUpgrade(SQLiteDatabase db int oldVersion int newVersion)
sql query to drop an existing table normally here alter table query is written but it is
just an example
dbexecSQL(DROP TABLE IF EXISTS +student_TABLE_NAME + )
Logging a tag for debugging purpose
Logd(DATABASE_NAME onupdate)
now calling onCreate to create table again
onCreate(db)
Explaination
Constructor it is used to create an object of this class and call constructor of super class
onCreate() onCreate() is called by android framework when we call getWritableDatabase() or
getReadableDatbase() methods it is called when database file is not present
onUpgrade() it is called whenever a new version of datbase become available such that definition
of database is changed a new column has been added datatype of a column is changed etc
student Class
package commujadid001 public class student data memebers private int id private String Name public int marks constructors public student(String name int marks) Name = name thismarks = marks public student(int id String name int marks) super() thisid = id Name = name thismarks = marks setters and getters public int getId() return id public void setId(int id) thisid = id
public String getName() return Name public void setName(String name) Name = name public int getMarks() return marks public void setMarks(int marks) thismarks = marks
Explanation student class is self explanatory it has member variables getters setters
construtors
DAO CLASS
package commujadid001
import androidcontentContentValues
import androidcontentContext
import androiddatabaseCursor
import androiddatabasesqliteSQLiteDatabase
import androidutilLog
DAO class
public class DAO
an object of class SQLiteDatabase which have built in functions to manipulate database
SQLiteDatabase db
creating a reference of class DBCreator
DBCreator dbcreator
creating an object of type Context
Context context
constructor
public DAO(Context context)
initializing data members
dbcreator=new DBCreator(context)
getting writable datbase from class DBCreator this method is inherited in
DBCreator from its parent
db=dbcreatorgetWritableDatabase()
method to insert a record
public int InsertRecord(student s)
try
sql query to insert a record
String sql=inser+DBCreatorstudent_TABLE_NAME+(studentNameMarks)
values(+sgetName()++sgetMarks()+ )
executing sql query
dbexecSQL(sql)
return 1
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOInsert)
return -1
method to delete a record
public int DeleteRecord(int id)
try
using built in delete function of class SQLitDatabase
return dbdelete(DBCreatorstudent_TABLE_NAME studentId= new
String[]+id)
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
delete(String table String whereClause String[] whereArgs)
this method is used to delete a record from database table
update (String table ContentValues contentValuesString whereClause String[] whereArgs)
this method is used to delete a record from database table
this method is used to select records from database table and return cursor object we
will learn cursor a little bit later
ltExamplerawQuery(select from users where uid = new String[] id )
query(String table String[] columns String selection String[] Args String
groupByClause String havingClause String orderByClause String
NoOfRowsToBeFethed)
this method executes given query and return cursor object
6 Cursor
Cursor is just like ResultSet in java It contains all the records retrieved in form of result
of a query Cursor has number of methods to manipulate returned data Some of them
are as follow
MoveToNext() Move cursor to next record
MoveToPrevious() Move cursor to previous record
MoveToFirst() Move cursor to first record
MoveToLast() Move cursor to last record
MoveToPosition(int p) Move cursor to a record at given position
isFirst() Returns true if it is first record
isLast() Returns true if it is last record
getString(int columnIndex) Return String stored at given column of a row
getInt(int columnIndex) Return integer value stored at given column of a row
getDouble(int columnIndex) Return double value stored at given column of a row
Creating an application that explain working with database
In this example I have made 5 activities first is main activity and a DataBase helper class named
as DBCreator and a student class as Data Transfer Object(DTO) and a DAO class that interact with
database
Letrsquos start with class DBCreater code is given below
package commujadid001
import androidcontentContext
import androiddatabasesqliteSQLiteDatabase
import androiddatabasesqliteSQLiteDatabaseCursorFactory
import androiddatabasesqliteSQLiteOpenHelper
import androidutilLog
public class DBCreator extends SQLiteOpenHelper
constatns to refer database file table name and datbase version
public static final String student_TABLE_NAME = Student
public static final String DATABASE_NAME = studentsResultsdb
private static int DATABASE_VERSION = 1
constructor it only calls super class constructor
public DBCreator(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
TODO Auto-generated constructor stub
onCreat() method is called to create database first time
Override
public void onCreate(SQLiteDatabase db)
sql query to create a table
String sql = CREATE TABLE + student_TABLE_NAME + (studentId INTEGER
PRIMARY KEY AUTOINCREMENT studentName TEXTMarks INTEGER)
Logging a tag for debugging purposes
Logd(DATABASE_NAME oncreate+sql)
executing sql query
dbexecSQL(sql)
onupgrade() method definition
Override
public void onUpgrade(SQLiteDatabase db int oldVersion int newVersion)
sql query to drop an existing table normally here alter table query is written but it is
just an example
dbexecSQL(DROP TABLE IF EXISTS +student_TABLE_NAME + )
Logging a tag for debugging purpose
Logd(DATABASE_NAME onupdate)
now calling onCreate to create table again
onCreate(db)
Explaination
Constructor it is used to create an object of this class and call constructor of super class
onCreate() onCreate() is called by android framework when we call getWritableDatabase() or
getReadableDatbase() methods it is called when database file is not present
onUpgrade() it is called whenever a new version of datbase become available such that definition
of database is changed a new column has been added datatype of a column is changed etc
student Class
package commujadid001 public class student data memebers private int id private String Name public int marks constructors public student(String name int marks) Name = name thismarks = marks public student(int id String name int marks) super() thisid = id Name = name thismarks = marks setters and getters public int getId() return id public void setId(int id) thisid = id
public String getName() return Name public void setName(String name) Name = name public int getMarks() return marks public void setMarks(int marks) thismarks = marks
Explanation student class is self explanatory it has member variables getters setters
construtors
DAO CLASS
package commujadid001
import androidcontentContentValues
import androidcontentContext
import androiddatabaseCursor
import androiddatabasesqliteSQLiteDatabase
import androidutilLog
DAO class
public class DAO
an object of class SQLiteDatabase which have built in functions to manipulate database
SQLiteDatabase db
creating a reference of class DBCreator
DBCreator dbcreator
creating an object of type Context
Context context
constructor
public DAO(Context context)
initializing data members
dbcreator=new DBCreator(context)
getting writable datbase from class DBCreator this method is inherited in
DBCreator from its parent
db=dbcreatorgetWritableDatabase()
method to insert a record
public int InsertRecord(student s)
try
sql query to insert a record
String sql=inser+DBCreatorstudent_TABLE_NAME+(studentNameMarks)
values(+sgetName()++sgetMarks()+ )
executing sql query
dbexecSQL(sql)
return 1
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOInsert)
return -1
method to delete a record
public int DeleteRecord(int id)
try
using built in delete function of class SQLitDatabase
return dbdelete(DBCreatorstudent_TABLE_NAME studentId= new
String[]+id)
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
Letrsquos start with class DBCreater code is given below
package commujadid001
import androidcontentContext
import androiddatabasesqliteSQLiteDatabase
import androiddatabasesqliteSQLiteDatabaseCursorFactory
import androiddatabasesqliteSQLiteOpenHelper
import androidutilLog
public class DBCreator extends SQLiteOpenHelper
constatns to refer database file table name and datbase version
public static final String student_TABLE_NAME = Student
public static final String DATABASE_NAME = studentsResultsdb
private static int DATABASE_VERSION = 1
constructor it only calls super class constructor
public DBCreator(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
TODO Auto-generated constructor stub
onCreat() method is called to create database first time
Override
public void onCreate(SQLiteDatabase db)
sql query to create a table
String sql = CREATE TABLE + student_TABLE_NAME + (studentId INTEGER
PRIMARY KEY AUTOINCREMENT studentName TEXTMarks INTEGER)
Logging a tag for debugging purposes
Logd(DATABASE_NAME oncreate+sql)
executing sql query
dbexecSQL(sql)
onupgrade() method definition
Override
public void onUpgrade(SQLiteDatabase db int oldVersion int newVersion)
sql query to drop an existing table normally here alter table query is written but it is
just an example
dbexecSQL(DROP TABLE IF EXISTS +student_TABLE_NAME + )
Logging a tag for debugging purpose
Logd(DATABASE_NAME onupdate)
now calling onCreate to create table again
onCreate(db)
Explaination
Constructor it is used to create an object of this class and call constructor of super class
onCreate() onCreate() is called by android framework when we call getWritableDatabase() or
getReadableDatbase() methods it is called when database file is not present
onUpgrade() it is called whenever a new version of datbase become available such that definition
of database is changed a new column has been added datatype of a column is changed etc
student Class
package commujadid001 public class student data memebers private int id private String Name public int marks constructors public student(String name int marks) Name = name thismarks = marks public student(int id String name int marks) super() thisid = id Name = name thismarks = marks setters and getters public int getId() return id public void setId(int id) thisid = id
public String getName() return Name public void setName(String name) Name = name public int getMarks() return marks public void setMarks(int marks) thismarks = marks
Explanation student class is self explanatory it has member variables getters setters
construtors
DAO CLASS
package commujadid001
import androidcontentContentValues
import androidcontentContext
import androiddatabaseCursor
import androiddatabasesqliteSQLiteDatabase
import androidutilLog
DAO class
public class DAO
an object of class SQLiteDatabase which have built in functions to manipulate database
SQLiteDatabase db
creating a reference of class DBCreator
DBCreator dbcreator
creating an object of type Context
Context context
constructor
public DAO(Context context)
initializing data members
dbcreator=new DBCreator(context)
getting writable datbase from class DBCreator this method is inherited in
DBCreator from its parent
db=dbcreatorgetWritableDatabase()
method to insert a record
public int InsertRecord(student s)
try
sql query to insert a record
String sql=inser+DBCreatorstudent_TABLE_NAME+(studentNameMarks)
values(+sgetName()++sgetMarks()+ )
executing sql query
dbexecSQL(sql)
return 1
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOInsert)
return -1
method to delete a record
public int DeleteRecord(int id)
try
using built in delete function of class SQLitDatabase
return dbdelete(DBCreatorstudent_TABLE_NAME studentId= new
String[]+id)
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
onCreat() method is called to create database first time
Override
public void onCreate(SQLiteDatabase db)
sql query to create a table
String sql = CREATE TABLE + student_TABLE_NAME + (studentId INTEGER
PRIMARY KEY AUTOINCREMENT studentName TEXTMarks INTEGER)
Logging a tag for debugging purposes
Logd(DATABASE_NAME oncreate+sql)
executing sql query
dbexecSQL(sql)
onupgrade() method definition
Override
public void onUpgrade(SQLiteDatabase db int oldVersion int newVersion)
sql query to drop an existing table normally here alter table query is written but it is
just an example
dbexecSQL(DROP TABLE IF EXISTS +student_TABLE_NAME + )
Logging a tag for debugging purpose
Logd(DATABASE_NAME onupdate)
now calling onCreate to create table again
onCreate(db)
Explaination
Constructor it is used to create an object of this class and call constructor of super class
onCreate() onCreate() is called by android framework when we call getWritableDatabase() or
getReadableDatbase() methods it is called when database file is not present
onUpgrade() it is called whenever a new version of datbase become available such that definition
of database is changed a new column has been added datatype of a column is changed etc
student Class
package commujadid001 public class student data memebers private int id private String Name public int marks constructors public student(String name int marks) Name = name thismarks = marks public student(int id String name int marks) super() thisid = id Name = name thismarks = marks setters and getters public int getId() return id public void setId(int id) thisid = id
public String getName() return Name public void setName(String name) Name = name public int getMarks() return marks public void setMarks(int marks) thismarks = marks
Explanation student class is self explanatory it has member variables getters setters
construtors
DAO CLASS
package commujadid001
import androidcontentContentValues
import androidcontentContext
import androiddatabaseCursor
import androiddatabasesqliteSQLiteDatabase
import androidutilLog
DAO class
public class DAO
an object of class SQLiteDatabase which have built in functions to manipulate database
SQLiteDatabase db
creating a reference of class DBCreator
DBCreator dbcreator
creating an object of type Context
Context context
constructor
public DAO(Context context)
initializing data members
dbcreator=new DBCreator(context)
getting writable datbase from class DBCreator this method is inherited in
DBCreator from its parent
db=dbcreatorgetWritableDatabase()
method to insert a record
public int InsertRecord(student s)
try
sql query to insert a record
String sql=inser+DBCreatorstudent_TABLE_NAME+(studentNameMarks)
values(+sgetName()++sgetMarks()+ )
executing sql query
dbexecSQL(sql)
return 1
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOInsert)
return -1
method to delete a record
public int DeleteRecord(int id)
try
using built in delete function of class SQLitDatabase
return dbdelete(DBCreatorstudent_TABLE_NAME studentId= new
String[]+id)
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
now calling onCreate to create table again
onCreate(db)
Explaination
Constructor it is used to create an object of this class and call constructor of super class
onCreate() onCreate() is called by android framework when we call getWritableDatabase() or
getReadableDatbase() methods it is called when database file is not present
onUpgrade() it is called whenever a new version of datbase become available such that definition
of database is changed a new column has been added datatype of a column is changed etc
student Class
package commujadid001 public class student data memebers private int id private String Name public int marks constructors public student(String name int marks) Name = name thismarks = marks public student(int id String name int marks) super() thisid = id Name = name thismarks = marks setters and getters public int getId() return id public void setId(int id) thisid = id
public String getName() return Name public void setName(String name) Name = name public int getMarks() return marks public void setMarks(int marks) thismarks = marks
Explanation student class is self explanatory it has member variables getters setters
construtors
DAO CLASS
package commujadid001
import androidcontentContentValues
import androidcontentContext
import androiddatabaseCursor
import androiddatabasesqliteSQLiteDatabase
import androidutilLog
DAO class
public class DAO
an object of class SQLiteDatabase which have built in functions to manipulate database
SQLiteDatabase db
creating a reference of class DBCreator
DBCreator dbcreator
creating an object of type Context
Context context
constructor
public DAO(Context context)
initializing data members
dbcreator=new DBCreator(context)
getting writable datbase from class DBCreator this method is inherited in
DBCreator from its parent
db=dbcreatorgetWritableDatabase()
method to insert a record
public int InsertRecord(student s)
try
sql query to insert a record
String sql=inser+DBCreatorstudent_TABLE_NAME+(studentNameMarks)
values(+sgetName()++sgetMarks()+ )
executing sql query
dbexecSQL(sql)
return 1
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOInsert)
return -1
method to delete a record
public int DeleteRecord(int id)
try
using built in delete function of class SQLitDatabase
return dbdelete(DBCreatorstudent_TABLE_NAME studentId= new
String[]+id)
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
public String getName() return Name public void setName(String name) Name = name public int getMarks() return marks public void setMarks(int marks) thismarks = marks
Explanation student class is self explanatory it has member variables getters setters
construtors
DAO CLASS
package commujadid001
import androidcontentContentValues
import androidcontentContext
import androiddatabaseCursor
import androiddatabasesqliteSQLiteDatabase
import androidutilLog
DAO class
public class DAO
an object of class SQLiteDatabase which have built in functions to manipulate database
SQLiteDatabase db
creating a reference of class DBCreator
DBCreator dbcreator
creating an object of type Context
Context context
constructor
public DAO(Context context)
initializing data members
dbcreator=new DBCreator(context)
getting writable datbase from class DBCreator this method is inherited in
DBCreator from its parent
db=dbcreatorgetWritableDatabase()
method to insert a record
public int InsertRecord(student s)
try
sql query to insert a record
String sql=inser+DBCreatorstudent_TABLE_NAME+(studentNameMarks)
values(+sgetName()++sgetMarks()+ )
executing sql query
dbexecSQL(sql)
return 1
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOInsert)
return -1
method to delete a record
public int DeleteRecord(int id)
try
using built in delete function of class SQLitDatabase
return dbdelete(DBCreatorstudent_TABLE_NAME studentId= new
String[]+id)
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
creating a reference of class DBCreator
DBCreator dbcreator
creating an object of type Context
Context context
constructor
public DAO(Context context)
initializing data members
dbcreator=new DBCreator(context)
getting writable datbase from class DBCreator this method is inherited in
DBCreator from its parent
db=dbcreatorgetWritableDatabase()
method to insert a record
public int InsertRecord(student s)
try
sql query to insert a record
String sql=inser+DBCreatorstudent_TABLE_NAME+(studentNameMarks)
values(+sgetName()++sgetMarks()+ )
executing sql query
dbexecSQL(sql)
return 1
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOInsert)
return -1
method to delete a record
public int DeleteRecord(int id)
try
using built in delete function of class SQLitDatabase
return dbdelete(DBCreatorstudent_TABLE_NAME studentId= new
String[]+id)
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
executing sql query
dbexecSQL(sql)
return 1
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOInsert)
return -1
method to delete a record
public int DeleteRecord(int id)
try
using built in delete function of class SQLitDatabase
return dbdelete(DBCreatorstudent_TABLE_NAME studentId= new
String[]+id)
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
logging if any exception occurs
Loge(DB etoString()+ DAOdelete)
return -1
public int UpdateRecord(student s)
try
creating an object of type ContentValues (explained already in tutorial)
ContentValues values=new ContentValues()
storing kay value pairs in it
valuesput(studentName sgetName())
valuesput(marks sgetMarks())
calling built in update function of class SQLitDatabase
return dbupdate(DBCreatorstudent_TABLE_NAME values studentId=
new String[] StringvalueOf(sgetId()))
catch(Exception e)
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
logging if any exception occurs
Loge(DB etoString()+ DAOUpdateRecord)
return -1
getting all records
public Cursor GetRecords()
now I have used rawQuery function of class SQLitDatabase
Cursor c=dbrawQuery(select from +DBCreatorstudent_TABLE_NAMEnull)
returning an object of class Cursor(explained already in tutorial)
return c
closing databse
public void close()
dbclose()
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
activity_mainxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=MainActivity gt lt-- creating a button --gt ltButton androidid=+idadd androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginTop=43dp androidlayout_weight=1 androidtext=stringAdd androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idremove androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idadd androidlayout_alignBottom=+idadd androidlayout_alignParentRight=true androidlayout_marginRight=25dp androidtext=stringremove androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idselect androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idadd androidlayout_marginTop=50dp androidtext=stringselect androidonClick=onClick gt lt-- creating a button --gt ltButton androidid=+idupdate androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignBaseline=+idselect
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
androidlayout_alignBottom=+idselect androidlayout_alignRight=+idremove androidtext=stringupdate androidonClick=onClick gt
ltRelativeLayoutgt
MainActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidcontentIntent
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
public class MainActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_main)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_main menu)
return true
onclick method to handle click event of buttons
Override
public void onClick(View view)
switch(viewgetId())
case Ridadd
creating an intent to goto activity to add a new record
Intent it=new Intent(MainActivitythisAddActivityclass)
starting new activity
startActivity(it)
break
case Ridremove
creating an intent to goto activity to select all records
it=new Intent(MainActivitythisDeleteActivityclass)
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
starting new activity
startActivity(it)
break
case Ridselect
creating an intent to goto activity to delete a record
it=new Intent(MainActivitythisSelectActivityclass)
starting new activity
startActivity(it)
break
case Ridupdate
creating an intent to goto activity to update a record
it=new Intent(MainActivitythisUpdateActivityclass)
starting new activity
startActivity(it)
break
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
ExplanationMainActivity is very simple it has only one clickListener method onClick to handle click
events an intent to desired activity is created and activity is started
Activity_addxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=AddActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringsname gt ltEditText androidid=+ideditText1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentRight=true androidlayout_below=+idtextView1 androidems=10 androidinputType=textPersonName gt ltrequestFocus gt ltEditTextgt ltTextView androidid=+idtextView2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ideditText1 androidtext=stringmarks gt ltEditText androidid=+ideditText2 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignRight=+idtextView1 androidlayout_below=+idtextView2 androidems=10 androidinputType=numberDecimalgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
androidlayout_height=wrap_content androidlayout_alignBaseline=+ideditText2 androidlayout_alignBottom=+ideditText2 androidlayout_marginLeft=35dp androidlayout_toRightOf=+idtextView2 androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
AddActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class AddActivity extends Activity implements OnClickListener
data members
String name
int marks
student s
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_add)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_add menu)
return true
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
overriden onClick method called when button is clicked
Override
public void onClick(View v)
getting value of editText Field
String temp=((EditText)findViewById(RideditText2))getText()toString()
parsing it into integers
marks=IntegerparseInt(temp)
getting value of editText Field
name=((EditText)findViewById(RideditText1))getText()toString()
creating an DTO object of type student
s=new student(namemarks)
creating an object of DAO class
DAO dao=new DAO(AddActivitythis)
calling its method insert
int i=daoInsertRecord(s)
checking if return value is +ve then its mean a record is inserted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() 1 record has been
added ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() record has not been
added ToastLENGTH_LONG)show()
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
finishing this activity
finish()
Explanation in activity_addxml we have two edittext and a button when a button is clicked
we get value of edit text field and make an object of class students and call method of DAO
class insertRecord() when a record is inserted a message is displayed and activity is
finished
DELETE A RECORD
activity_ deletexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=DeleteActivity gt ltEditText androidid=+ididfield androidlayout_width=50dp androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidems=10 androidhint=id androidinputType=number gt ltrequestFocus gt ltEditTextgt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_centerHorizontal=true androidonClick=onClick androidtext=stringsubmit gt
ltRelativeLayoutgt
DeleteActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class DeleteActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_delete)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_delete menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield))getText()toString()
parsing it into integers
int deleteID=IntegerparseInt(id)
creating an anonymous object of DAO class and calling deleteRecord
method
int i=new DAO(DeleteActivitythis)DeleteRecord(deleteID)
checking if return value is +ve then its mean record has deleted else an
error has occured
if(igt0)
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
ToastmakeText(getApplicationContext() i+ record has been
deleted ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in delete_activityxml we have one edittext and a button when a button is clicked we
get value of edit text field and call method of DAO class DeleteRecord() when a record is deleted a
message is displayed and activity is finished
UPDATE A RECORD
activity_ updatexml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=UpdateActivity gt ltTextView androidid=+idtextView1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_alignParentTop=true androidtext=stringprompt gt ltEditText androidid=+idmarksPrompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+idnameprompt androidlayout_marginTop=19dp androidems=10 androidhint=enter marks androidinputType=phone gt ltrequestFocus gt ltEditTextgt ltEditText
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
androidid=+ididfield2 androidlayout_width=60dp androidlayout_height=wrap_content androidlayout_alignParentTop=true androidlayout_marginLeft=14dp androidlayout_toRightOf=+idnameprompt androidems=10 androidhint=id androidinputType=phone gt ltButton androidid=+idbutton1 androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_below=+idmarksPrompt androidlayout_marginTop=56dp androidlayout_toRightOf=+idtextView1 androidonClick=onClick androidtext=stringsubmit gt ltEditText androidid=+idnameprompt androidlayout_width=wrap_content androidlayout_height=wrap_content androidlayout_alignParentLeft=true androidlayout_below=+ididfield2 androidems=10 androidhint=Enter new name androidinputType=textPersonName gt
ltRelativeLayoutgt
UpdateActivityjava
package commujadid001
import androidosBundle
import androidappActivity
import androidviewMenu
import androidviewView
import androidviewViewOnClickListener
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
import androidwidgetEditText
import androidwidgetToast
public class UpdateActivity extends Activity implements OnClickListener
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_update)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_update menu)
return true
Override
public void onClick(View v)
getting value of editText Field
String id=((EditText)findViewById(Rididfield2))getText()toString()
parsing it into integers
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
int ID=IntegerparseInt(id)
String mark=((EditText)findViewById(RidmarksPrompt))getText()toString()
parsing it into integers
int marks=IntegerparseInt(mark)
getting value of editText Field
String name=((EditText)findViewById(Ridnameprompt))getText()toString()
creating an DTO object of type student
student s=new student(IDnamemarks)
creating an object of DAO class
DAO dao=new DAO(UpdateActivitythis)
calling its method updateRecord
int i=daoUpdateRecord(s)
checking if return value is +ve then its mean a record is updated else an error has occured
if(igt0)
displaying message
ToastmakeText(getApplicationContext() 1 record has been updated
ToastLENGTH_LONG)show()
else
ToastmakeText(getApplicationContext() no record has added
ToastLENGTH_LONG)show()
finish()
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
Explanation in update_activityxml we have three edittext fields and a button when a button is
clicked we get value of all edit text fields make an object of class student and call method of DAO
class UpdateRecord() when a record is updated a message is displayed and activity is finished
Displaying all records
activity_selectxml
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid xmlnstools=httpschemasandroidcomtools androidlayout_width=match_parent androidlayout_height=match_parent toolscontext=SelectActivity gt ltListView androidid=+idlist1 androidlayout_height=fill_parent androidlayout_width=fill_parent gtltListViewgt
ltRelativeLayoutgt
SelectActivityjava
package commujadid001
import javautilArrayList
import androidosBundle
import androidappActivity
import androiddatabaseCursor
import androidviewMenu
import androidwidgetArrayAdapter
import androidwidgetListView
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
import androidwidgetToast
public class SelectActivity extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutactivity_select)
getting reference to listview
ListView lv=(ListView) findViewById(Ridlist1)
creating an object of type ArrayList
ArrayListltStringgt al=new ArrayListltStringgt()
creating an anonymous object of DAO class and calling getRecords method and
storing in Cursor object
Cursor c=new DAO(this)GetRecords()
Adding all records in cursor into arraylist object
while(cmoveToNext())
getting integer value of first column
int id=cgetInt(0)
getting string value of 2nd column
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
String name=cgetString(1)
getting integer value of 3rd column
int marks=cgetInt(2)
adding them in to array list
aladd(+id+ +name+ +marks)
creating an array adapter
ArrayAdapterltStringgt adapter=new
ArrayAdapter(thisandroidRlayoutsimple_list_item_1al)
setting adapter to list
lvsetAdapter(adapter)
Override
public boolean onCreateOptionsMenu(Menu menu)
Inflate the menu this adds items to the action bar if it is present
getMenuInflater()inflate(Rmenuactivity_select menu)
return true
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut
Explanation In select_actictyxml we have only a listView in java class we get reference to this
listview
After that we make an object of arraylist of type string we create an object of DAO class and called
method getRecords() which returns a cursor object we received cursor object an iterate over it to
get all records and save them in arrayList then we made an object of type arrayAdapter and then
set it to list
Sample OutPut