SQLite Database CRUD Tutorial for Android
SQLite Database CRUD Tutorial for Android
Android
Prepared by: Joseph Azar
Objectives
• In this tutorial, you will save the data to the SQLite database.
the help of a simple example and perform some basic operations (CRUD) of SQLite.
oC: Create
or: Read
oU: Update
oD: Delete
• You will learn to use the MVC (Model-View-Controller) framework. You will separate
your project in packages of models, views, and controllers in order to better structure the
project
• You will discover the LayoutInflater and its use.
• You will discover the ScrollView element
• You will create a view (e.g., TextView) programmatically using Java.
• You will learn to use AlertDialog
Introduction
SQLite is a lightweight database that is already integrated into the Android framework. It is a
open source database that only takes 250 KB of memory at runtime.
The SQLite database supports a limited number of data types. These types
data are:
• Text
• Integer
• Real
• BLOB
Thus, all other data types must be converted into the data types mentioned.
before inserting them into the database. SQLite supports features
1
standard relational database such as SQL syntax, transactions and the
prepared syntax.
2
Create a database
Then create a new class named SQLiteHelper and extend it with the class
SQLiteOpenHelper is a helper class that manages the creation and
database version management of SQLite in Android. Thus, in the class
SQLiteHelper, we will implement the methods onCreate(), onUpgrade() and onOpen()
of the SQLiteOpenHelper class to create the table for our application.
We are going to create a student table with three columns: ID of integer type, Name of type
text and group of type text.
3
4
In the code above, we created a database table to store the
student information. Here, we retrieve the SQLiteDatabase instance and create a
new database table using the onCreate() method of our class
assistance. Now, we can create methods to perform various operations
related to the database.
Create two packages, respectively Managers and Views. Move the MainActivity class to
the package Viewset the class SQLiteHelper to the package Managers
5
Create a student model
Create a new package 'Models'. Under this package, create a new class 'Student'.
La classeStudentsera utilisée pour instancier des objetsstudentque nous utiliserons pour
insert and extract data from the database.
6
Insert information into the database
Next, we need to create a method that will perform the insertion operation. So,
start by getting write access to our database using:
SQLiteDatabase db = [Link]();
7
Ensuite, créez un objetContentValueset ajoutez les informations à l’objet à insérer.
ContentValues is essentially a class used to store a set of values.
that can be handled by ContentResolver.
Finally, using the insert() method of the database instance, add the values to the
desired table. We need to pass the name of the database table and the object
ContentValues as arguments for the insert() method. Also close access to the
database once the insertion is completed.
SQLiteDatabase db = [Link]();
8
Then we will use the method query() to implement the condition and retrieve the
table data. It returns an objectCursor through which we can iterate the entire set
results. Here is the method example to retrieve the data based on a
condition:
publicStudent getStudent(intid) {
SQLiteDatabase db =[Link]();
Cursor cursor = [Link](dbHelper.TABLE_STUDENTS, newString[] { dbHelper.KEY_ID,
dbHelper.KEY_NAME, dbHelper.KEY_GROUP}, dbHelper.KEY_ID+ "=?",
newString[] { [Link](id) }null, null, null, null);
if(cursor != null)
[Link]();
Student student =newStudent([Link]([Link](0)),
[Link](1), [Link](2);
returnstudent
}
Pour récupérer les informations complètes présentes dans la table de base de données, nous
we need write access to our database instance. This looks more like
an SQL query where we select all the data from the table. To perform this
operation, we will use the rawQuery() method of the database instance. It
will return a Cursor object that we will use to extract the entire set of results. Here is
the example code for retrieving the data:
9
publicList<Student> getAllStudents() {
SQLiteDatabase db = [Link]();
List<Student> studentList = newArrayList<Student>();
String selectQuery = SELECT * FROM + dbHelper.TABLE_STUDENTS;
Cursor cursor = [Link](selectQuery,null);
if([Link]()) {
do{
Student student =newStudent([Link]([Link](0)),
[Link](1),[Link](2);
[Link](student);
} while([Link]());
}
returnstudentList;
}
10
Delete information from the database
To delete entries from the database table, we need to define a criterion for
Selection to identify the entries to delete. We will therefore use the delete() method.
from the database that requires three arguments:
• Database name
• Selection clause ('Where')
• Selection argument
Combined, these arguments will create a delete request that will work exactly
in the same way as an SQL query. Here is the code example to delete the data
from the table:
public voiddeleteStudent(Student student) {
SQLiteDatabase db = [Link]();
[Link](dbHelper.TABLE_STUDENTS, dbHelper.KEY_ID + " = ?",
newString[] { [Link]([Link]()) });
[Link]();
}
11
We have now finished with the package managers and models in which we
We have created the database operations. We will now create the views.
12
We are going to define the OnClickListener for the 'Create a student' button.
The following code will be placed in the onCreate() method, under setContentView
([Link].activity_main); code from your [Link] file.
13
Prepare the input form for a student.
Right-click on res/layout/è Click on 'New'è Click on "File"> Name it
student_input_form.xml
<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editTextStudentname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:hint="Nom de l'etudiant"
android:singleLine="true">
<requestFocus/>
</EditText>
<EditText
android:id="@+id/editTextStudentGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editTextStudentname"
android:hint="Groupe de l'etudiant"
android:singleLine="true"/>
</RelativeLayout>
14
Show the 'create a student' form to the user
Return and open your class '[Link]'.
Add the following code to your class (under the onClick(View view) function) to open the
Create a student.
[Link](context)
.setView(formElementsView)
.setTitle(Create a student)
.setPositiveButton(Add,
[Link]() {
public voidonClick(DialogInterface dialog,intid) {
[Link]();
}
}).show();
15
Note:
The LayoutInflater class is used to instantiate the XML layout file into objects.
View correspondents.
In other words, it takes an XML file as input and builds the objects view from it.
this one.
Inflater means reading the XML file that describes a layout (or GUI element) and creating the
real objects that correspond to it, thus making the object visible in an Android application.
If you run the application after adding the code above. After pressing the
button 'Create a student', you should get the result below:
16
Record the user's input
Open the class OnClickListenerCreateStudent. In the onClick() method of AlertDialog, we
We will record the student's information.
Using the already created StudentHandler class in the Managers package, we will
save the entered information
[Link](context)
.setView(formElementsView)
.setTitle(Create a student)
.setPositiveButton(Add,
[Link]() {
public voidonClick(DialogInterface dialog,intid) {
Student student=newStudent();
String studentName =[Link]().toString();
String studentGroup =
[Link]().toString();
[Link](studentName);
[Link](studentGroup);
intcreatedStudent= new
StudentHandler(context).addStudent(student);
[Link]();
}
).show();
17
Count the records in the Android database
SQLite
In your layout/activity_main.xml, place a TextView under your 'Create a' button.
student
18
Now, we want to create the method count in the class Managers/StudentHandler.
Ouvrez la classe StudentHandler et ajoutez la méthode ci-dessous:
public intcount() {
SQLiteDatabase db = [Link]();
String sql = SELECT * FROM + dbHelper.TABLE_STUDENTS;
intrecordCount = [Link](sql,null).getCount();
[Link]();
returnrecordCount;
}
19
Open the MainActivity class, create the countRecords() method, and call it in onCreate()
We also want to display the number of students in the database after having
registered a new student. Open the classOnClickListenerCreateStudent and add the
method countRecords after creating a new student to update the TextView value.
20
[Link](context)
.setView(formElementsView)
.setTitle(Create a student)
.setPositiveButton(Add,
[Link]() {
public voidonClick(DialogInterface dialog,intid) {
Student student=newStudent();
String studentName =[Link]().toString();
String studentGroup =
[Link]().toString();
[Link](studentName);
[Link](studentGroup);
intcreatedStudent= new
StudentHandler(context).addStudent(student);
}).show();
21
Run your application and try to create a new student. When the application is
created for the first time, it displays the text '0 records found'. After creating
a new student, it will display '1 record found'
22
Read records from the SQLite database
Open the file res/layout/activity_main.xml and place a ScrollView with a LinearLayout.
the interior under the TextView 'textViewRecordCount'.
23
In your [Link], create the method readRecords(). This will display the
database records on the user interface.
public voidreadRecords() {
if([Link]() > 0) {
intid = [Link]();
String studentName = [Link]();
String studentgroup = [Link]();
else{
24
We will now create the method readRecords() in the class in the same way.
OnClickListenerCreateStudent when we create a new student to update the
content of ScrollView.
25
public voidreadRecords(Context context,View view) {
if([Link]() > 0) {
intid = [Link]();
String studentName = [Link]();
String studentgroup = [Link]();
else{
26
[Link](context)
.setView(formElementsView)
.setTitle(Create a student)
.setPositiveButton(Add,
[Link]() {
public voidonClick(DialogInterface dialog,intid) {
Student student=newStudent();
String studentName =[Link]().toString();
String studentGroup =
[Link]().toString();
[Link](studentName);
[Link](studentGroup);
intcreatedStudent= new
StudentHandler(context).addStudent(student);
}).show();
27
28
Now, launch the application and try to create new students. The list of
students must appear as shown in the image below:
29
Define OnLongClickListener for each of the records to display. Access your
[Link]è readRecords (),dans la boucle ‘for’, placez le code suivant sous
[Link]([Link](id));
To test the above code, launch the application and long press on a student.
TextView. The dialogue below should appear:
30
In the onClick() method of the AlertDialog, in the onLongClick(view) method of the class
OnLongClickListenerStudentRecord, insert the following code. “Modify” has an index of 0.
@Override
public booleanonLongClick(finalView view) {
context = [Link]();
id= [Link]().toString();
[Link](context).setTitle(Student File)
.setItems(items,[Link]() {
public voidonClick(DialogInterface dialog,intitem) {
if(item == 0) {
editRecord([Link](id),view);
}
[Link]();
}
}).show();
return false;
}
31
public voideditRecord(final intstudentId,finalView view) {
LayoutInflater inflater = (LayoutInflater)
[Link](Context.LAYOUT_INFLATER_SERVICE);
finalView formElementsView = [Link]([Link] input form, null,
false);
[Link]([Link]());
[Link]([Link]());
[Link](context)
.setView(formElementsView)
.setTitle(Update the information)
.setPositiveButton(Save,
[Link]() {
public voidonClick(DialogInterface dialog,intid) {
Student objectStudent = newStudent();
[Link](studentId);
[Link]([Link]().toString());
[Link]([Link]().toString());
intupdatedStudent=new
StudentHandler(context).updateStudent(objectStudent);
}).show();
Finally, add the methods countRecordset readRecords (the same as those created in the)
classeOnClickListenerCreateStudent) à la classeOnLongClickListenerStudentRecordet appelez-
in the method editRecord in order to update the graphical interface after an operation
of update.
32
public voidcountRecords(Context context,View view) {
intstudentCount = newStudentHandler(context).count();
TextView textViewRecordCount = (TextView)
[Link]().findViewById([Link]);
[Link](studentCount + records found.);
}
if([Link]() > 0) {
intid = [Link]();
String studentName = [Link]();
String studentgroup = [Link]();
else{
33
34
Now, test your application and make sure that the update operation works
correctly.
35
Delete a record in Android SQLite
Access your [Link]è onLongClick ()è in
the method AlertDialog onClick(). Put the following code after the first if statement:
@Override
public booleanonLongClick(finalView view) {
context= [Link]();
id= [Link]().toString();
[Link](context).setTitle(Student File)
.setItems(items, [Link]() {
public voidonClick(DialogInterface dialog,intitem) {
if(item == 0) {
editRecord([Link](id),view);
}else if(item == 1) {
Student student = newStudent();
[Link]([Link](id));
newStudentHandler([Link](student);
[Link](context, Record successfully deleted,
Toast.SHORT_LENGTH).show();
countRecords(context,view);
readRecords(context,view);
}
[Link]();
}
}).show();
return false;
}
36
Launch the application and perform the deletion operation.
37