SlideShare ist ein Scribd-Unternehmen logo
1 von 6
Android Training – Steps to Work with SQLite Database for Data Management
SQLite is an open source database that provides a facility for storing and management of the user data
in Android device. This is present in every device having Android OS and hence needs to be handled
CRUD (Create, Read, Update & Delete) functionalities for data management.
In this article, we are going to learn about the easy ways to create a table in the database, add and read
data from it, upgrade the existing table data and finally delete the data.
Now let us take an example of storing the trainee details in the database. For this here we are using the
Class called Trainee to store the details. This table contains three columns – first is to store the ID of the
trainee, second stores the name of the student and the last third column is used to store name of the
course the trainee has joined.
Field
Trainee_ID
Trainee_Name
Course_Name

Type
Int
Text
Text

Key
Primary Key

Step 1: Defining the Trainee Class
Now initially we will define the Trainee class using the get and set methods.
For Example:
Trainee.java
package com.androidhive.androidsqlite;
public class Trainee
{
//We declare the variables to be used in the class. These are the private variables.
int _trainee_id;
String _trainee_name;
String _course_name;
// Empty constructor to prevent someone from accidentally instantiating the trainee class
public Trainee()
{
}
// Constructor
public Trainee(int trainee_id, String trainee_name, String course_name){
this._ trainee_id = trainee_id;
this._ trainee_name = trainee_name;
this._ course_name = course_name;
}
// Get & Set the Trainee ID
public int getTraineeID()
{
return this._ trainee_id;//getting ID
}
public void setTraineeID(int trainee_id)
{
this._ trainee_id = trainee_id; // setting id
}
// Get & Set Trainee Name
public String getTraineeName()
{
return this._ trainee_name; // getting name
}
public void setTraineeName(String trainee_name)
{
this._ trainee_name = trainee_name; // setting name
}
// Get & Set Course Name

}

public String getCourseName()
{
return this._ course_name; // getting course name
}
public void setCourseName(String course_name)
{
this._ course_name = course_name; // setting course name
}

Step 2: Defining a CustomDatabaseHandler Class to handle all the database operations
Now we will create a class CustomDatabaseHandler that extends from the SQLiteOpenHelper class. The
SQLiteOpenHelper class is used for database creation. This class will automatically create a database if it
does not exist already or otherwise open the database if it exists and thus helps to implement the
upgrading processes as necessary.
As we create a subclass of SQLiteOpenHelper class we are required to redefine its methods
on Create(SQLiteDatabase db) and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) in the
subclass. onCreate method is called for creating tables and onUpgrade method is to upgrade the table
with modifications if any.
For Example:
public class CustomDatabaseHandler extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION = 1; // defining the database version is mandatory
private static final String DATABASE_NAME = "traineeManager"; // Database Name
private static final String TABLE_NAME = "traineeDetails"; // table name
private static final String MAIN_TRAINEE_ID = "trainee_id";
private static final String MAIN_TRAINEE _NAME = "trainee_name";
private static final String MAIN_COURSE_NAME = "course_name";
public CustomDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Override onCreate method to create table
public void onCreate(SQLiteDatabase db) {
String CREATE_TRAINEE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ MAIN_TRAINEE_ID + " INTEGER PRIMARY KEY," + MAIN_TRAINEE _NAME + " TEXT,"
+ MAIN_ COURSE_NAME + " TEXT" + ")";
db.execSQL(CREATE_ TRAINEE _TABLE);
}
// Override onUpgrade method
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); //drop the table if there already exists table
with this name
onCreate(db);//Hence, create new table once again
}
Step 3: Inserting Data into the Table
Once we have created a table, our next step is to add data into the table. For this we will create a class
ContentValues and hence, by passing the object of this class to insert method we will insert the data into
database.
public void addTraineeDetails(Trainee trainee)
{
CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());//instantiate the
subclass of SQLiteOpenHelper Class
SQLiteDatabase db = cDbHelper.getWritableDatabase();//Setting the database in write mode to allow
insertion of values
ContentValues values = new ContentValues();
values.put(MAIN_TRAINEE_ID, trainee.getTraineeID();//This calls the getTraineeID() method that was
defined in Trainee.java
values.put(MAIN_TRAINEE_NAME, trainee.getTraineeName());//This calls the getTraineeName() method
that was defined in Trainee.java
values.put(MAIN_COURSE_NAME, trainee.getCourseName()); //This calls the getCourseName() method
that was defined in Trainee.java
db.insert(TABLE_NAME, null, values);//Inserting Values into Database
db.close(); // Closing database connection upon completion of insert task
}
Step 4: Reading the Data from Database Table
Now, we are ready to display or read the data present in the table. Following code shows how we can
derive all trainee details present in the database in array list format of Trainee class type. Here we are
using the if and do-while loops to extract each and every row data from the table
public List<Trainee> getAllTraineeDetails() {// getAllTraineeDetails() will return all trainee details from
database in array list format
List<Trainee> traineeList = new ArrayList<Trainee>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());
SQLiteDatabase db = cDbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {//loop to derive all the values
do {
Trainee trainee = new Trainee();
trainee.setTraineeID(Integer.parseInt(cursor.getString(0)));//Here the setTraineeID method that
was defined in Trainee.java
trainee.setTraineeName(cursor.getString(1)); //Here the setTraineeName method that was
defined in Trainee.java
trainee.setCourseName(cursor.getString(2)); //Here the setCourseName method that was defined
in Trainee.java
traineeList.add(trainee);//adding the retrieved values to the created arraylist
} while (cursor.moveToNext());
}
return traineeList;//return the list of
}
Step 5: Updating the Table
We are now updating a single trainee details in database using the updateTrainee method that takes
object of the Trainee class as parameter.
public int updateTrainee(Trainee trainee) {
CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());//setting the
database write mode
SQLiteDatabase db = cDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MAIN_TRAINEE_NAME, trainee.getTraineeName());
values.put(MAIN_COURSE_NAME, trainee.getCourseName());
return db.update(TABLE_NAME, values, MAIN_TRAINEE_ID + " = ?",
new String[] { String.valueOf(Trainee.getTraineeID()) });
}
Step 6: Deleting the Data from Table
Finally we are deleting a single trainee details from the database using the deleteTrainee method that
takes object of Trainee class as parameter.
public void deleteTrainee(Trainee trainee) {
CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());//setting the
database write mode
SQLiteDatabase db = cDbHelper.getWritableDatabase();
db.delete(TABLE_NAME, MAIN_TRAINEE_ID + " = ?",
new String[] { String.valueOf(Trainee.getTraineeID()) });
db.close();
}
Hence, by using the above mentioned steps one can perform SQLite database operations for the
Android apps. This allows the developer to create a mechanism to store data in the android device
database.
Android training is the best way to learn this SQLite database activity for data storage. TOPS
Technologies provides Android training on SQLite concepts to the learners so that they can get familiar
with effective database handling concepts including methods to add, update and delete content from
SQLite, SQLiteOpenHelper class and data types used in this database.
CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());//setting the
database write mode
SQLiteDatabase db = cDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MAIN_TRAINEE_NAME, trainee.getTraineeName());
values.put(MAIN_COURSE_NAME, trainee.getCourseName());
return db.update(TABLE_NAME, values, MAIN_TRAINEE_ID + " = ?",
new String[] { String.valueOf(Trainee.getTraineeID()) });
}
Step 6: Deleting the Data from Table
Finally we are deleting a single trainee details from the database using the deleteTrainee method that
takes object of Trainee class as parameter.
public void deleteTrainee(Trainee trainee) {
CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());//setting the
database write mode
SQLiteDatabase db = cDbHelper.getWritableDatabase();
db.delete(TABLE_NAME, MAIN_TRAINEE_ID + " = ?",
new String[] { String.valueOf(Trainee.getTraineeID()) });
db.close();
}
Hence, by using the above mentioned steps one can perform SQLite database operations for the
Android apps. This allows the developer to create a mechanism to store data in the android device
database.
Android training is the best way to learn this SQLite database activity for data storage. TOPS
Technologies provides Android training on SQLite concepts to the learners so that they can get familiar
with effective database handling concepts including methods to add, update and delete content from
SQLite, SQLiteOpenHelper class and data types used in this database.

Weitere ähnliche Inhalte

Andere mochten auch

Android Protips: Advanced Topics for Expert Android App Developers
Android Protips: Advanced Topics for Expert Android App DevelopersAndroid Protips: Advanced Topics for Expert Android App Developers
Android Protips: Advanced Topics for Expert Android App DevelopersReto Meier
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mappingAbhilash M A
 
Object Relational model for SQLIite in android
Object Relational model for SQLIite  in android Object Relational model for SQLIite  in android
Object Relational model for SQLIite in android yugandhar vadlamudi
 
Python PPT
Python PPTPython PPT
Python PPTEdureka!
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 

Andere mochten auch (6)

Android Protips: Advanced Topics for Expert Android App Developers
Android Protips: Advanced Topics for Expert Android App DevelopersAndroid Protips: Advanced Topics for Expert Android App Developers
Android Protips: Advanced Topics for Expert Android App Developers
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
 
Object Relational model for SQLIite in android
Object Relational model for SQLIite  in android Object Relational model for SQLIite  in android
Object Relational model for SQLIite in android
 
Design and Concepts of Android Graphics
Design and Concepts of Android GraphicsDesign and Concepts of Android Graphics
Design and Concepts of Android Graphics
 
Python PPT
Python PPTPython PPT
Python PPT
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Mehr von TOPS Technologies

Learn java objects inheritance-overriding-polymorphism
Learn java objects  inheritance-overriding-polymorphismLearn java objects  inheritance-overriding-polymorphism
Learn java objects inheritance-overriding-polymorphismTOPS Technologies
 
Surat tops conducted one hour seminar on “corporate basic skills”
Surat tops conducted  one hour seminar on “corporate basic skills”Surat tops conducted  one hour seminar on “corporate basic skills”
Surat tops conducted one hour seminar on “corporate basic skills”TOPS Technologies
 
Word press interview question and answer tops technologies
Word press interview question and answer   tops technologiesWord press interview question and answer   tops technologies
Word press interview question and answer tops technologiesTOPS Technologies
 
Software testing and quality assurance
Software testing and quality assuranceSoftware testing and quality assurance
Software testing and quality assuranceTOPS Technologies
 
Learn advanced java programming
Learn advanced java programmingLearn advanced java programming
Learn advanced java programmingTOPS Technologies
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applicationsTOPS Technologies
 
What is ui element in i phone developmetn
What is ui element in i phone developmetnWhat is ui element in i phone developmetn
What is ui element in i phone developmetnTOPS Technologies
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applicationsTOPS Technologies
 
Software testing live project training
Software testing live project trainingSoftware testing live project training
Software testing live project trainingTOPS Technologies
 
Web designing live project training
Web designing live project trainingWeb designing live project training
Web designing live project trainingTOPS Technologies
 
iPhone training in ahmedabad by tops technologies
iPhone training in ahmedabad by tops technologiesiPhone training in ahmedabad by tops technologies
iPhone training in ahmedabad by tops technologiesTOPS Technologies
 
08 10-2013 gtu projects - develop final sem gtu project in i phone
08 10-2013 gtu projects - develop final sem gtu project in i phone08 10-2013 gtu projects - develop final sem gtu project in i phone
08 10-2013 gtu projects - develop final sem gtu project in i phoneTOPS Technologies
 
GTU PHP Project Training Guidelines
GTU PHP Project Training GuidelinesGTU PHP Project Training Guidelines
GTU PHP Project Training GuidelinesTOPS Technologies
 
GTU Asp.net Project Training Guidelines
GTU Asp.net Project Training GuidelinesGTU Asp.net Project Training Guidelines
GTU Asp.net Project Training GuidelinesTOPS Technologies
 

Mehr von TOPS Technologies (20)

Learn java objects inheritance-overriding-polymorphism
Learn java objects  inheritance-overriding-polymorphismLearn java objects  inheritance-overriding-polymorphism
Learn java objects inheritance-overriding-polymorphism
 
Surat tops conducted one hour seminar on “corporate basic skills”
Surat tops conducted  one hour seminar on “corporate basic skills”Surat tops conducted  one hour seminar on “corporate basic skills”
Surat tops conducted one hour seminar on “corporate basic skills”
 
Word press interview question and answer tops technologies
Word press interview question and answer   tops technologiesWord press interview question and answer   tops technologies
Word press interview question and answer tops technologies
 
How to install android sdk
How to install android sdkHow to install android sdk
How to install android sdk
 
Software testing and quality assurance
Software testing and quality assuranceSoftware testing and quality assurance
Software testing and quality assurance
 
Basics in software testing
Basics in software testingBasics in software testing
Basics in software testing
 
Learn advanced java programming
Learn advanced java programmingLearn advanced java programming
Learn advanced java programming
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applications
 
What is ui element in i phone developmetn
What is ui element in i phone developmetnWhat is ui element in i phone developmetn
What is ui element in i phone developmetn
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applications
 
Java live project training
Java live project trainingJava live project training
Java live project training
 
Software testing live project training
Software testing live project trainingSoftware testing live project training
Software testing live project training
 
Web designing live project training
Web designing live project trainingWeb designing live project training
Web designing live project training
 
Php live project training
Php live project trainingPhp live project training
Php live project training
 
iPhone training in ahmedabad by tops technologies
iPhone training in ahmedabad by tops technologiesiPhone training in ahmedabad by tops technologies
iPhone training in ahmedabad by tops technologies
 
Php training in ahmedabad
Php training in ahmedabadPhp training in ahmedabad
Php training in ahmedabad
 
Java training in ahmedabad
Java training in ahmedabadJava training in ahmedabad
Java training in ahmedabad
 
08 10-2013 gtu projects - develop final sem gtu project in i phone
08 10-2013 gtu projects - develop final sem gtu project in i phone08 10-2013 gtu projects - develop final sem gtu project in i phone
08 10-2013 gtu projects - develop final sem gtu project in i phone
 
GTU PHP Project Training Guidelines
GTU PHP Project Training GuidelinesGTU PHP Project Training Guidelines
GTU PHP Project Training Guidelines
 
GTU Asp.net Project Training Guidelines
GTU Asp.net Project Training GuidelinesGTU Asp.net Project Training Guidelines
GTU Asp.net Project Training Guidelines
 

Kürzlich hochgeladen

BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Kürzlich hochgeladen (20)

BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Android training easy steps to work with sqlite database for data management

  • 1. Android Training – Steps to Work with SQLite Database for Data Management SQLite is an open source database that provides a facility for storing and management of the user data in Android device. This is present in every device having Android OS and hence needs to be handled CRUD (Create, Read, Update & Delete) functionalities for data management. In this article, we are going to learn about the easy ways to create a table in the database, add and read data from it, upgrade the existing table data and finally delete the data. Now let us take an example of storing the trainee details in the database. For this here we are using the Class called Trainee to store the details. This table contains three columns – first is to store the ID of the trainee, second stores the name of the student and the last third column is used to store name of the course the trainee has joined. Field Trainee_ID Trainee_Name Course_Name Type Int Text Text Key Primary Key Step 1: Defining the Trainee Class Now initially we will define the Trainee class using the get and set methods. For Example: Trainee.java package com.androidhive.androidsqlite; public class Trainee { //We declare the variables to be used in the class. These are the private variables. int _trainee_id; String _trainee_name; String _course_name; // Empty constructor to prevent someone from accidentally instantiating the trainee class public Trainee() { } // Constructor public Trainee(int trainee_id, String trainee_name, String course_name){ this._ trainee_id = trainee_id; this._ trainee_name = trainee_name; this._ course_name = course_name; } // Get & Set the Trainee ID
  • 2. public int getTraineeID() { return this._ trainee_id;//getting ID } public void setTraineeID(int trainee_id) { this._ trainee_id = trainee_id; // setting id } // Get & Set Trainee Name public String getTraineeName() { return this._ trainee_name; // getting name } public void setTraineeName(String trainee_name) { this._ trainee_name = trainee_name; // setting name } // Get & Set Course Name } public String getCourseName() { return this._ course_name; // getting course name } public void setCourseName(String course_name) { this._ course_name = course_name; // setting course name } Step 2: Defining a CustomDatabaseHandler Class to handle all the database operations Now we will create a class CustomDatabaseHandler that extends from the SQLiteOpenHelper class. The SQLiteOpenHelper class is used for database creation. This class will automatically create a database if it does not exist already or otherwise open the database if it exists and thus helps to implement the upgrading processes as necessary. As we create a subclass of SQLiteOpenHelper class we are required to redefine its methods on Create(SQLiteDatabase db) and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) in the subclass. onCreate method is called for creating tables and onUpgrade method is to upgrade the table with modifications if any.
  • 3. For Example: public class CustomDatabaseHandler extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; // defining the database version is mandatory private static final String DATABASE_NAME = "traineeManager"; // Database Name private static final String TABLE_NAME = "traineeDetails"; // table name private static final String MAIN_TRAINEE_ID = "trainee_id"; private static final String MAIN_TRAINEE _NAME = "trainee_name"; private static final String MAIN_COURSE_NAME = "course_name"; public CustomDatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Override onCreate method to create table public void onCreate(SQLiteDatabase db) { String CREATE_TRAINEE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + MAIN_TRAINEE_ID + " INTEGER PRIMARY KEY," + MAIN_TRAINEE _NAME + " TEXT," + MAIN_ COURSE_NAME + " TEXT" + ")"; db.execSQL(CREATE_ TRAINEE _TABLE); } // Override onUpgrade method public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); //drop the table if there already exists table with this name onCreate(db);//Hence, create new table once again } Step 3: Inserting Data into the Table Once we have created a table, our next step is to add data into the table. For this we will create a class ContentValues and hence, by passing the object of this class to insert method we will insert the data into database. public void addTraineeDetails(Trainee trainee) { CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());//instantiate the subclass of SQLiteOpenHelper Class SQLiteDatabase db = cDbHelper.getWritableDatabase();//Setting the database in write mode to allow insertion of values ContentValues values = new ContentValues();
  • 4. values.put(MAIN_TRAINEE_ID, trainee.getTraineeID();//This calls the getTraineeID() method that was defined in Trainee.java values.put(MAIN_TRAINEE_NAME, trainee.getTraineeName());//This calls the getTraineeName() method that was defined in Trainee.java values.put(MAIN_COURSE_NAME, trainee.getCourseName()); //This calls the getCourseName() method that was defined in Trainee.java db.insert(TABLE_NAME, null, values);//Inserting Values into Database db.close(); // Closing database connection upon completion of insert task } Step 4: Reading the Data from Database Table Now, we are ready to display or read the data present in the table. Following code shows how we can derive all trainee details present in the database in array list format of Trainee class type. Here we are using the if and do-while loops to extract each and every row data from the table public List<Trainee> getAllTraineeDetails() {// getAllTraineeDetails() will return all trainee details from database in array list format List<Trainee> traineeList = new ArrayList<Trainee>(); String selectQuery = "SELECT * FROM " + TABLE_NAME; CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext()); SQLiteDatabase db = cDbHelper.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) {//loop to derive all the values do { Trainee trainee = new Trainee(); trainee.setTraineeID(Integer.parseInt(cursor.getString(0)));//Here the setTraineeID method that was defined in Trainee.java trainee.setTraineeName(cursor.getString(1)); //Here the setTraineeName method that was defined in Trainee.java trainee.setCourseName(cursor.getString(2)); //Here the setCourseName method that was defined in Trainee.java traineeList.add(trainee);//adding the retrieved values to the created arraylist } while (cursor.moveToNext()); } return traineeList;//return the list of } Step 5: Updating the Table We are now updating a single trainee details in database using the updateTrainee method that takes object of the Trainee class as parameter. public int updateTrainee(Trainee trainee) {
  • 5. CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());//setting the database write mode SQLiteDatabase db = cDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(MAIN_TRAINEE_NAME, trainee.getTraineeName()); values.put(MAIN_COURSE_NAME, trainee.getCourseName()); return db.update(TABLE_NAME, values, MAIN_TRAINEE_ID + " = ?", new String[] { String.valueOf(Trainee.getTraineeID()) }); } Step 6: Deleting the Data from Table Finally we are deleting a single trainee details from the database using the deleteTrainee method that takes object of Trainee class as parameter. public void deleteTrainee(Trainee trainee) { CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());//setting the database write mode SQLiteDatabase db = cDbHelper.getWritableDatabase(); db.delete(TABLE_NAME, MAIN_TRAINEE_ID + " = ?", new String[] { String.valueOf(Trainee.getTraineeID()) }); db.close(); } Hence, by using the above mentioned steps one can perform SQLite database operations for the Android apps. This allows the developer to create a mechanism to store data in the android device database. Android training is the best way to learn this SQLite database activity for data storage. TOPS Technologies provides Android training on SQLite concepts to the learners so that they can get familiar with effective database handling concepts including methods to add, update and delete content from SQLite, SQLiteOpenHelper class and data types used in this database.
  • 6. CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());//setting the database write mode SQLiteDatabase db = cDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(MAIN_TRAINEE_NAME, trainee.getTraineeName()); values.put(MAIN_COURSE_NAME, trainee.getCourseName()); return db.update(TABLE_NAME, values, MAIN_TRAINEE_ID + " = ?", new String[] { String.valueOf(Trainee.getTraineeID()) }); } Step 6: Deleting the Data from Table Finally we are deleting a single trainee details from the database using the deleteTrainee method that takes object of Trainee class as parameter. public void deleteTrainee(Trainee trainee) { CustomDatabaseHandler cDbHelper = new CustomDatabaseHandler((getContext());//setting the database write mode SQLiteDatabase db = cDbHelper.getWritableDatabase(); db.delete(TABLE_NAME, MAIN_TRAINEE_ID + " = ?", new String[] { String.valueOf(Trainee.getTraineeID()) }); db.close(); } Hence, by using the above mentioned steps one can perform SQLite database operations for the Android apps. This allows the developer to create a mechanism to store data in the android device database. Android training is the best way to learn this SQLite database activity for data storage. TOPS Technologies provides Android training on SQLite concepts to the learners so that they can get familiar with effective database handling concepts including methods to add, update and delete content from SQLite, SQLiteOpenHelper class and data types used in this database.