Title: SQLite Database Tutorial In Android
1SQLite Database Tutorial In Android
Posted on J uly 9, 2018 by Bhadresh
SQLite Database in Android used to s tore
persistent data. If you want to s tore some data
into local s torage then SQLite Database is the
most common s torage option. It is lightweight
database that comes with Android OS. In Android
There are others data s torage options also
available Like Shared Preference to s tore small
amount of data in form of Key / Value pair.
SQLite Database File System Here we are going to
learn how to use SQLite Database in Android
application. SQLite is an open source SQL
database which s tore the data into text le on
android device. SQLite database in android also
support relational database features. In order
to access SQLite Database you dont need to
establish any kind of connections like J DBC,
ODBC. 1. Overview In this tutorial we are going
to create Student App to learn all the operation
related the SQLite Database. The app is very s
imple and which allow us to insert, update,
delete and view s tudent data. We will use 2
screen to perform all this operations. In rs t
screen we fetch full lis t of s tudent from the s
tudent table while using second screen update or
add new s tudent record. Following is the
Student app screen shot.
2- Now lets start by creating new project in
Android Studio. - 2. Create / Setup Project
- Create a new project in Android Studio from File
? New Project and select Basic Activity from the
templates. - Open build.gradle under app directory and add
CardView library. CardView is used to display
Student List inside the Card.
1 2 3 4 5 6 7 8 dependencies //... implementation 'com.android.supportcardview-v727.1.1' //...
3. Add following code into colors.xml and
strings.xml files. colors.xml
colors.xml colors.xml
1 lt?xml version"1.0" encoding"utf-8"?gt
2 ltresourcesgt
3 ltcolor name"colorPrimary"gt3F51B5lt/colorgt
4 ltcolor name"colorPrimaryDark"gt303F9Flt/colorgt
5 ltcolor name"colorAccent"gtFF4081lt/colorgt
6 ltcolor name"mainText"gt212121lt/colorgt
7 ltcolor name"subText"gt737373lt/colorgt
8 ltcolor name"view"gtc0c0c0lt/colorgt
9 ltcolor name"colorWhite"gtfffffflt/colorgt
10 lt/resourcesgt
3strings.xml
strings.xml strings.xml
1 2 3 4 5 6 7 8 9 10 ltresourcesgt ltstring name"app_name"gtStudent Managementlt/stringgt ltstring name"strAddNewStudent"gtAdd New Studentlt/stringgt ltstring name"strUpdateStudent"gtUpdate Studentlt/stringgt ltstring name"strDelete"gtDeletelt/stringgt ltstring name"strStudentName"gtEnter Student Namelt/stringgt ltstring name"strStudentResult"gtEnter Pass/Faillt/stringgt ltstring name"strStudentGrade"gtEnter Gradelt/stringgt ltstring name"strSave"gtSavelt/stringgt lt/resourcesgt
4. Create following packages named adapter, db,
model and ui. The following is the final project
structure and files are required.
3. Create SQLite Helper Classes 5. In this
tutorial we have taken student example to perform
all operation. So first we need to create one
model class named StudentInfo.java under model
package. StudentInfo.java contain student
information like id, name, grade and result.
Further we will used this class to store and
retrieve student information from the SQLite
database.
StudentInfo.java StudentInfo.java
1 public class StudentInfo
2
3 int studentId
4 String studentName, studentResult, studentGrade
5
6 public StudentInfo()
7
8
9
10 public StudentInfo(int studentId)
11 this.studentId studentId
12
13
14 public StudentInfo(String studentName, String studentResult, String studentGrade)
15 this.studentName studentName
16 this.studentResult studentResult
17 this.studentGrade studentGrade
18
19
20 public StudentInfo(int studentId, String studentName, String studentResult, String studentGrade)
21 this.studentId studentId
22 this.studentName studentName
23 this.studentResult studentResult
24 this.studentGrade studentGrade
25
26
27 public int getStudentId()
28 return studentId
429 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
public void setStudentId(int studentId)
this.studentId studentId
public String getStudentName() return
studentName
public void setStudentName(String studentName)
this.studentName studentName
public String getStudentResult() return
studentResult
public void setStudentResult(String
studentResult) this.studentResult
studentResult
public String getStudentGrade() return
studentGrade
public void setStudentGrade(String studentGrade)
this.studentGrade studentGrade
56
57 6. Now we need to create a class that
extends from SQLiteOpenHelper. So create
DBHelper.java under db package. DBHelper.java
perform all the database operations like Create,
Update, Delete and Read. Before the proceed
lets understand use of all the methods and table
structure of the StudentInfo. onCreate() method
will be called only once when application launch
first time in android phone. So from this method
we will execute sql statement to create Student
table. onUpgrade() method will be called when
update the application. You need to change the
DB_VERSION in order to execute this methods. The
StudentInfo table needs four column _id, name,
result and grade. Column _id is declared as
Primary Key and Auto Increment which means it is
unique key to identify the Students. name
contains student name, result is ether pass or
fail, grade contains student grade. So let add
the following code into DBHelper Class.
DBHelper.java DBHelper.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 public class DBHelper extends SQLiteOpenHelper // Database Name static final String DATABASE "student.db" // Database Version static final int DB_VERSION 1 // Table Name static final String TABLE "StudentInfo" // Table Field Name static final String S_ID "_id" static final String S_NAME "name" static final String S_RESULT "result" static final String S_GRADE "grade" // Override constructor public DBHelper(Context context) super(context, DATABASE, null, DB_VERSION) _at_Override public void onCreate(SQLiteDatabase db) // Create StudentInfo table using SQL query db.execSQL("CREATE TABLE " TABLE " ( " S_ID " INTEGER PRIMARY KEY AUTOINCREMENT, " S_NAME " text, " S_RESULT " text, " S_GRADE " text )") _at_Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
534 35 36 37 38
// Drop old version table db.execSQL("Drop table
" TABLE)
// Create New Version table onCreate(db)
39
40 7. Now we need to implement four methods to
perform CRUD Create, Read, Update, Delete
operations with student data. Lets have look of
each methods. 7.1 Insert Student Data Inserting
data requires writable instance of the
SQLiteDatabase So Create instance using
getWritableDatabase(). ContentValues() is used
to add database values in respective column. So
setup all the value with respective column in
ContentValues(), Skip _id because its auto
inserted. Close the database connection after
inserting is done.
addStudentDetails addStudentDetails
1 public void addStudentDetails(StudentInfo studInfo)
2
3 SQLiteDatabase db this.getWritableDatabase()
4
5 ContentValues values new ContentValues()
6 values.put(S_NAME, studInfo.getStudentName())
7 values.put(S_RESULT, studInfo.getStudentResult())
8 values.put(S_GRADE, studInfo.getStudentGrade())
9 10 // Inserting Row
11 db.insert(TABLE, null, values)
12 db.close()
13
7.2 Update Student Data. Updating data also
requiring writable access of the SQLiteDatabase.
Student data will be updated using _id column.
updateStudentDetails updateStudentDetails
1 public int updateStudentDetails(StudentInfo studInfo)
2
3 SQLiteDatabase db this.getWritableDatabase()
4
5 ContentValues values new ContentValues()
6 values.put(S_NAME, studInfo.getStudentName())
7 values.put(S_RESULT, studInfo.getStudentResult())
8 values.put(S_GRADE, studInfo.getStudentGrade())
9 10 // updating row
11 return db.update(TABLE, values, S_ID " ?",
12 new StringString.valueOf(studInfo.getStudentId()))
13
7.3 Delete Student Data. To delete student data
we also required to declare SQLiteDatabase
instance with writable access. The following
methods will be Delete specified student record
from the database using _id
deleteStudentDetails deleteStudentDetails
1 2 3 4 5 6 7 8 public void deleteStudentDetails(StudentInfo studentInfo) SQLiteDatabase db this.getWritableDatabase() db.delete(TABLE, S_ID " ?", new StringString.valueOf(studentInfo.getStudentId())) db.close()
7.4 Fetch Student Data To read data from the
database table requires SQLiteDatabase instance
as a read access. For that we can
define SQLiteDatabase instance using
getReadableDatabase(). Following method will
fetch all students data from the database table.
getStudentDetails getStudentDetails
1 public ListltStudentInfogt getStudentDetails()
62 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2
1 22 23 24 25
ListltStudentInfogt StudentList new ArrayListltgt()
// Select All Query String selectQuery "SELECT
FROM " TABLE SQLiteDatabase db
this.getWritableDatabase() Cursor cursor
db.rawQuery(selectQuery, null)
// looping through all rows and adding to list if
(cursor.moveToFirst()) do StudentInfo
studentInfo new StudentInfo()
studentInfo.setStudentId(cursor.getInt(0))
studentInfo.setStudentName(cursor.getString(1))
studentInfo.setStudentResult(cursor.getString(2))
studentInfo.setStudentGrade(cursor.getString(3))
// Adding student information to
list StudentList.add(studentInfo) while
(cursor.moveToNext())
cursor.close() return StudentList
26 So add all above methods into
DBHelper.java class, The final code of the
DBHelper.java class looks like this.
DBHelper.java DBHelper.java
1 package dwi.db.operations.student.management.db
2 import android.content.ContentValues
3 import android.content.Context
4 import android.database.Cursor
5 import android.database.sqlite.SQLiteDatabase
6 import android.database.sqlite.SQLiteOpenHelper
7 import java.util.ArrayList
8 import java.util.List
9 import dwi.db.operations.student.management.model.StudentInfo
10 public class DBHelper extends SQLiteOpenHelper
11 12 // Static Final Variable database meta information
13 static final String DATABASE "student.db"
14 static final int DB_VERSION 1
15 static final String TABLE "StudentInfo"
16 static final String S_ID "_id"
17 static final String S_NAME "name"
18 static final String S_RESULT "result"
19 static final String S_GRADE "grade"
20 21 // Override constructor
22 public DBHelper(Context context)
23 super(context, DATABASE, null, DB_VERSION)
24
25
26 _at_Override
27 public void onCreate(SQLiteDatabase db)
28 // Create StudentInfo table using SQL query
29 db.execSQL("CREATE TABLE " TABLE " ( " S_ID
30 " INTEGER PRIMARY KEY AUTOINCREMENT, " S_NAME " text, "
31 S_RESULT " text, " S_GRADE " text )")
32
33
34 _at_Override
35 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
36 37 // Drop old version table
38 db.execSQL("Drop table " TABLE)
39 40 // Create New Version table
41 onCreate(db)
42
43 44 // Adding new detail
45 public void addStudentDetails(StudentInfo studInfo)
46 SQLiteDatabase db this.getWritableDatabase()
47 ContentValues values new ContentValues()
48 values.put(S_NAME, studInfo.getStudentName())
49 values.put(S_RESULT, studInfo.getStudentResult())
50 values.put(S_GRADE, studInfo.getStudentGrade())
51 // Inserting Row
52 db.insert(TABLE, null, values)
53 db.close() // Closing database connection
54
55 56 // Updating details
57 public int updateStudentDetails(StudentInfo studInfo)
58 SQLiteDatabase db this.getWritableDatabase()
59 ContentValues values new ContentValues()
7values.put(S_NAME, studInfo.getStudentName())
values.put(S_RESULT, studInfo.getStudentResult())
values.put(S_GRADE, studInfo.getStudentGrade())
// updating row return db.update(TABLE, values,
S_ID " ?", new StringString.valueOf(studInf
o.getStudentId()))
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 9
3 94 95 96 97 98
// Deleting single recoed public void
deleteStudentDetails(StudentInfo studentInfo)
SQLiteDatabase db this.getWritableDatabase()
db.delete(TABLE, S_ID " ?", new
StringString.valueOf(studentInfo.getStudentId()
)) db.close() // Get all student
information public ListltStudentInfogt
getStudentDetails() ListltStudentInfogt
StudentList new ArrayListltgt() // Select All
Query String selectQuery "SELECT FROM "
TABLE SQLiteDatabase db this.getWritableDataba
se() Cursor cursor db.rawQuery(selectQuery,
null) // looping through all rows and adding to
list if (cursor.moveToFirst()) do
StudentInfo studentInfo new StudentInfo()
studentInfo.setStudentId(cursor.getInt(0))
studentInfo.setStudentName(cursor.getString(1))
studentInfo.setStudentResult(cursor.getString(2))
studentInfo.setStudentGrade(cursor.getString(3))
// Adding student information to
list StudentList.add(studentInfo) while
(cursor.moveToNext()) cursor.close() return
StudentList
4. Create List Adapter 8. Create new layout
files under layout folder named
student_list_row.xml. This layout file holds
single items in list.
student_list_row.xml student_list_row.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 lt?xml version"1.0" encoding"utf-8"?gt ltLinearLayout xmlnsandroid"http//schemas.android.com/apk/res/android" xmlnsapp"http//schemas.android.com/apk/res-auto" xmlnscard_view"http//schemas.android.com/apk/res-auto" androidlayout_width"match_parent" androidlayout_height"match_parent" androidorientation"horizontal"gt ltandroid.support.v7.widget.CardView androidid"_at_id/card_view" androidlayout_width"fill_parent" androidlayout_height"wrap_content" androidlayout_marginTop"_at_dimen/_15sdp" androidlayout_marginLeft"_at_dimen/_5sdp" androidlayout_marginRight"_at_dimen/_5sdp" appcardBackgroundColor"FFFFFF" card_viewcardCornerRadius"2dp" card_viewcontentPadding"10dp"gt ltLinearLayout androidorientation"horizontal" androidlayout_width"match_parent" androidlayout_height"match_parent"gt ltLinearLayout androidorientation"vertical" androidlayout_weight"0.5" androidlayout_width"match_parent" androidlayout_height"match_parent"gt ltTextView androidid"_at_id/txtName" androidhint"Name" androidlayout_weight"6" androidtextSize"15dp" androidtextColor"000" androidlayout_gravity"center" androidlayout_width"match_parent" androidlayout_height"wrap_content" androidpadding"5dp" /gt ltTextView androidid"_at_id/txtStatus" androidhint"Status" androidlayout_weight"6" androidtextSize"15dp" androidtextColor"000" androidlayout_gravity"center" androidlayout_width"match_parent"
8androidlayout_height"wrap_content"
androidpadding"5dp" /gt ltTextView androidid"_at_i
d/txtGrade" androidhint"Grade"
androidlayout_weight"6" androidtextSize"15dp"
androidtextColor"000" androidlayout_gravity
"center" androidlayout_width"match_parent"
androidlayout_height"wrap_content"
androidpadding"5dp" /gt lt/LinearLayoutgt ltLinearLa
yout androidlayout_weight"1.9"
androidorientation"vertical"
androidlayout_width"match_parent"
androidlayout_height"match_parent"gt ltImageView a
ndroidid"_at_id/imgEdit" androidlayout_weight"2
" androidsrc"_at_drawable/ic_edit"
androidlayout_width"_at_dimen/_20sdp"
androidlayout_height"_at_dimen/_20sdp"
androidlayout_gravity"center" /gt ltImageView andr
oidid"_at_id/imgDelete" androidlayout_weight"2"
androidsrc"_at_drawable/ic_delete"
androidlayout_width"_at_dimen/_20sdp"
androidlayout_height"_at_dimen/_20sdp"
androidlayout_gravity"center" /gt lt/LinearLayoutgt
lt/LinearLayoutgt
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 7
7 78 79 80 81 82
lt/android.support.v7.widget.CardViewgt lt/LinearLayo
utgt
9. Now create the new class named
StudentListAdapter.java under adapter
package. This is the Student List adapter and it
will show you all the student records from the
database. From the list you can Delete or Update
particular student data by tapping on Delete or
Update button.
StudentListAdapter StudentListAdapter
1 public class StudentListAdapter extends ArrayAdapterltStudentInfogt
2 3 // Context Objects
4 Context context
5 MainActivity display_data
6 7 // Primitive Variables
8 public ListltStudentInfogt productList
9 public static LayoutInflater inflater null
10 11 // DB Objects
12 DBHelper db
13 public StudentListAdapter(_at_NonNull Context context, int resource, ListltStudentInfogt productList)
14 super(context, resource, productList)
15 this.context context
16 this.productList productList
17 db new DBHelper(context)
18 display_data (MainActivity) this.context
19 inflater (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
20
21
22 _at_Override
23 public StudentInfo getItem(int position)
24 return productList.get(position)
25
26
27 _at_NonNull
28 _at_Override
29 public View getView(int position, _at_Nullable View convertView, _at_NonNull ViewGroup parent)
30 ViewProHolder holder
31 if (convertView null)
32 View view inflater.inflate(R.layout.student_list_row, null)
33 holder ViewProHolder.create((LinearLayout) view)
34 view.setTag(holder)
35 else
36 holder (ViewProHolder) convertView.getTag()
37
38 try
39 final StudentInfo item getItem(position)
40 holder.txtName.setText(item.getStudentName())
941 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 7
4 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
106 107 108 109 110 111 112 113 114 115 116 117 1
18
holder.txtStatus.setText(item.getStudentResult())
holder.txtGrade.setText(item.getStudentGrade())
// Update Student Data holder.imgEdit.setOnClickL
istener(new View.OnClickListener()
_at_Override public void onClick(View v) Intent
intent new Intent(context, AddUpdateDetailsActiv
ity.class) intent.putExtra("sid",
item.getStudentId()) intent.putExtra("sname",
item.getStudentName()) intent.putExtra("sstatus"
, item.getStudentResult()) intent.putExtra("sgra
de", item.getStudentGrade()) MainActivity.oprati
on 1 display_data.startActivityForResult(intent
, 1) ) // Delete Student Data holder.imgDelet
e.setOnClickListener(new View.OnClickListener()
_at_Override public void onClick(View v) try
AlertDialog.Builder alertDialog new
AlertDialog.Builder(context) // Setting Dialog
Title alertDialog.setTitle("Confirm
Delete...") // Setting Dialog Message alertDialog
.setMessage("Are you sure you want delete
this?") // Setting Icon to Dialog alertDialog.set
Icon(R.drawable.ic_delete) // Setting Positive
"Yes" Button alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() public
void onClick(DialogInterface dialog, int which)
db.deleteStudentDetails(new StudentInfo(item.get
StudentId())) display_data.bindStudentData()
) // Setting Negative "NO" Button alertDialog.se
tNegativeButton("NO", new DialogInterface.OnClickL
istener() public void onClick(DialogInterface
dialog, int which) dialog.cancel() ) alertD
ialog.show() catch (Exception e)
Log.e("Error ", e.getMessage())
e.printStackTrace() ) catch (Exception
e) Log.e("Error in adapter ", e.getMessage())
e.printStackTrace() return holder.view
public static class ViewProHolder public final
LinearLayout view TextView txtName, txtStatus,
txtGrade ImageView imgEdit ImageView
imgDelete public ViewProHolder(LinearLayout
view, TextView tv_name, TextView tv_status,
TextView im_icon, ImageView im_edit, ImageView
im_delete) this.view view this.txtName
tv_name this.txtStatus tv_status
this.txtGrade im_icon this.imgEdit im_edit
this.imgDelete im_delete public static
ViewProHolder create(LinearLayout view) //
Widget GUI Init TextView tv_name
view.findViewById(R.id.txtName) TextView
tv_status view.findViewById(R.id.txtStatus)
TextView tv_grade view.findViewById(R.id.txtGrad
e) ImageView im_edit view.findViewById(R.id.im
gEdit) ImageView im_delete view.findViewById(R
.id.imgDelete) return new ViewProHolder(view,
tv_name, tv_status, tv_grade, im_edit,
im_delete)
119 5. Create Add / Update Activity 10. Create
new layout files under layout folder named
activity_add_update.xml. This the layout of Add /
Update student data activity.
activity_add_update.xml activity_add_update.xml
1 lt?xml version"1.0" encoding"utf-8"?gt
10ltLinearLayout xmlnsandroid"http//schemas.androi
d.com/apk/res/android" xmlnstools"http//schema
s.android.com/tools" androidlayout_width"match_
parent" androidlayout_height"match_parent" andr
oidorientation"vertical" toolscontext".ui.Add
UpdateDetailsActivity"gt ltTextView androidid"_at_id
/tvHeading" androidlayout_width"wrap_content"
androidlayout_height"wrap_content"
androidtext"_at_string/strAddNewStudent"
androidlayout_gravity"center"
androidgravity"center" androidpaddingTop"_at_dim
en/_15sdp" androidlayout_marginBottom"_at_dimen/_1
0sdp" androidtextSize"30sp" /gt ltLinearLayout
androidorientation"vertical"
androidpaddingLeft"_at_dimen/_15sdp"
androidpaddingRight"_at_dimen/_15sdp" androidlayou
t_height"wrap_content" androidlayout_width"matc
h_parent"gt ltEditText androidid"_at_id/etName"
androidlayout_width"match_parent"
androidlayout_height"wrap_content"
androidems"10" androidinputType"textEmailAddr
ess" androidmaxLines"1" androidtextSize"_at_dim
en/_12sdp" androidhint"_at_string/strStudentName"
androidlayout_marginBottom"_at_dimen/_5sdp"
androidtextColor"_at_color/mainText"
androidtextColorHint"_at_color/subText"
androidpaddingTop"_at_dimen/_10sdp"
androidpaddingBottom"_at_dimen/_5sdp"
androidbackground"_at_androidcolor/transparent"
/gt ltView androidlayout_width"fill_parent"
androidlayout_height"_at_dimen/_2sdp"
androidlayout_marginBottom"_at_dimen/_5sdp"
androidbackground"_at_color/view"/gt
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2
1 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 7
1 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
88 89 90 91
ltEditText androidid"_at_id/etStatus"
androidlayout_width"match_parent"
androidlayout_height"wrap_content"
androidems"10" androidinputType"textEmailAddr
ess" androidmaxLines"1" androidtextSize"_at_dim
en/_12sdp" androidhint"_at_string/strStudentResult
" androidlayout_marginBottom"_at_dimen/_5sdp"
androidtextColor"_at_color/mainText"
androidtextColorHint"_at_color/subText"
androidpaddingTop"_at_dimen/_10sdp"
androidpaddingBottom"_at_dimen/_5sdp"
androidbackground"_at_androidcolor/transparent"
/gt ltView androidlayout_width"fill_parent"
androidlayout_height"_at_dimen/_2sdp"
androidlayout_marginBottom"_at_dimen/_5sdp"
androidbackground"_at_color/view"/gt ltEditText andro
idid"_at_id/etGrade" androidlayout_width"match_
parent" androidlayout_height"wrap_content"
androidems"10" androidinputType"textEmailAddr
ess" androidmaxLines"1" androidtextSize"_at_dim
en/_12sdp" androidhint"_at_string/strStudentGrade"
androidlayout_marginBottom"_at_dimen/_5sdp"
androidtextColor"_at_color/mainText"
androidtextColorHint"_at_color/subText"
androidpaddingTop"_at_dimen/_10sdp"
androidpaddingBottom"_at_dimen/_5sdp"
androidbackground"_at_androidcolor/transparent"
/gt ltView androidlayout_width"fill_parent"
androidlayout_height"_at_dimen/_2sdp"
androidlayout_marginBottom"_at_dimen/_40sdp"
androidbackground"_at_color/view"/gt ltButton android
id"_at_id/btnSave" androidtext"_at_string/strSave"
androidlayout_gravity"center"
androidgravity"center" androidbackground"_at_col
or/colorAccent" androidtextColor"_at_color/colorWh
ite" androidlayout_width"wrap_content"
11androidpadding"_at_dimen/_10sdp"
androidlayout_height"wrap_content"
/gt lt/LinearLayoutgt lt/LinearLayoutgt
92 93 94 95
11. Now create the AddUpdateDetailsActivity.java
file under ui package. Using this class we can
perform Add / Update operations.
AddUpdateDetailsActivity.java AddUpdateDetailsActivity.java
1 public class AddUpdateDetailsActivity extends AppCompatActivity implements View.OnClickListener
2 3 // Primitive Variables
4 int strId
5 String strName, strStatus, strGrade
6 7 // DB Objects
8 public DBHelper db
9 10 // Widget GUI Declare
11 TextView tvHeading
12 EditText etName, etStatus, etGrade
13 Button btnSave
14
15 _at_Override
16 protected void onCreate(Bundle savedInstanceState)
17 super.onCreate(savedInstanceState)
18 setContentView(R.layout.activity_add_update)
19 getSupportActionBar().setDisplayHomeAsUpEnabled(true)
20 getSupportActionBar().setDisplayShowHomeEnabled(true)
21 22 // Initialize Database Instance
23 db new DBHelper(AddUpdateDetailsActivity.this)
24 etName findViewById(R.id.etName)
25 etStatus findViewById(R.id.etStatus)
26 etGrade findViewById(R.id.etGrade)
27 tvHeading findViewById(R.id.tvHeading)
28 btnSave findViewById(R.id.btnSave)
29 30 // Set Title According To Operation
31 if (opration 0)
32 tvHeading.setText("Add Student Data")
33 else
34 tvHeading.setText("Update Student Data")
35
36
37 Intent intent getIntent()
38 if (intent ! null)
39 strId intent.getIntExtra("sid", 0)
40 strName intent.getStringExtra("sname")
41 strStatus intent.getStringExtra("sstatus")
42 strGrade intent.getStringExtra("sgrade")
43 etName.setText(strName)
44 etStatus.setText(strStatus)
45 etGrade.setText(strGrade)
46
47 btnSave.setOnClickListener(this)
48
49
50 _at_Override
51 public boolean onSupportNavigateUp()
52 onBackPressed()
53 return true
54
55
56 _at_Override
57 public void onClick(View v)
58 if (v.getId() R.id.btnSave)
59 if (TextUtils.isEmpty(etName.getText()))
60 Toast.makeText(this, "Name is empty..!", Toast.LENGTH_SHORT).show()
61 else if (TextUtils.isEmpty(etStatus.getText()))
62 Toast.makeText(this, "Status is empty..!", Toast.LENGTH_SHORT).show()
63 else if (TextUtils.isEmpty(etGrade.getText()))
64 Toast.makeText(this, "Grade is empty..!", Toast.LENGTH_SHORT).show()
65 else
66 // get values from edittext
67 strName etName.getText().toString()
68 strStatus etStatus.getText().toString()
69 strGrade etGrade.getText().toString()
70 if (opration 0)
71 // Call insert method
72 addDetails()
73 else
74 // Call update method
75 updateDetails()
76
77
78
1279 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
96 97 98 99 100 101 102 103 104 105 106 107 108 1
09 110 111 112 113 114 115 116 117 118 119 120 121
122 123 124 125 126
// Call update method of SQLiteDatabase Class and
close after private void updateDetails()
Intent intent new Intent() try
db.updateStudentDetails(new StudentInfo(strId,
strName, strStatus, strGrade))
showRecords() intent.putExtra("msg", "Details
updated successfully..!") setResult(1,
intent) finish() catch (Exception e)
e.printStackTrace() intent.putExtra("msg",
"Update Failed..!") setResult(0,
intent) finish()
// Call insert method of SQLiteDatabase Class and
close after public void addDetails() Intent
intent new Intent() try db.addStudentDetails
(new StudentInfo(strName, strStatus, strGrade))
showRecords() intent.putExtra("msg", "Details
added successfully..!") setResult(1,
intent) finish() catch (Exception e)
e.printStackTrace() intent.putExtra("msg",
"added failed..!") setResult(0,
intent) finish()
// Reading all contacts public void showRecords()
Log.e("Reading ", "Reading all records..")
ListltStudentInfogt studentInfos
db.getStudentDetails() for (StudentInfo cn
studentInfos) String log "SId "
cn.getStudentId() " ,StudName "
cn.getStudentName() " StudStatus " cn.g
)
" StudeGrade " cn.getStudentGrade() //
Writing records to log Log.e("Student ", log)
6. Setup Main Activity 12. Finally open
MainActivity.java and add following code into
this. MainActivity will show you all the student
records in form of list. Using Floating Action
Button you can add new student data in
table. Edit Button allows to edit perticular
student data from the list. By tapping Delete
Button from the list you can delete particular
student data.
MainActivity.java MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public class MainActivity extends AppCompatActivity // Primitive Variables public static int opration ListltStudentInfogt mStudentInfoList // Widget GUI Declare ListView lstView FloatingActionButton fab // DB Objects DBHelper db // Adapter Object StudentListAdapter adapter _at_Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initialize Database Instance db new DBHelper(MainActivity.this) // Widget GUI Init
13l s t Vi ew f i ndVi ewBy I d( R. i d. l s t St
udent Det a i l s ) f ab f i ndVi ewBy I d(
R. i d. f ab)
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 5
9 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
93 94 95 96 97 98 99 100 101 102 103 104
/ / Fet c h Dat a f r om dat abas e bi ndSt udent
Dat a ( )
/ / At t ac hed L i s t ener f ab. s et OnCl i c
k L i s t ener ( new Vi ew. OnCl i c k L i s t
ener ( ) _at_Ov er r i de publ i c voi d onCl i c
k( Vi ew v) I nt ent i nt ent new I nt ent (
get Appl i c at i onCont ex t ( ) , AddUpdat e
Det a i l s Ac t i v i t y . c l as s ) opr at
i on 0 s t ar t Ac t i v i t y For Res ul t (
i nt ent , 1) )
/ / Get Al l St udent Dat a Fr om The Dat abas
e publ i c voi d bi ndSt udent Dat a ( ) mS t
udent I nf oL i s t db. get St udent Det a i l
s ( ) adapt er new St udent L i s t Adapt er
( Ma i nAc t i v i t y . t hi s , R. l ay out . s
t udent _ l i s t _ r ow, mS t udent I nf oL i s
t ) l s t Vi e w. s et Adapt er ( adapt er )
l s t Vi e w. s et E mpt y Vi e w( f i ndVi
ewBy I d( R. i d. e mpt y ) )
_at_Ov er r i de publ i c bool ean onCr eat e Opt i
ons Me nu( Me nu me nu) Me nuI nf l at er i nf
l at er get Me nuI nf l at er ( ) i nf l at
er . i nf l at e( R. me nu. me nu, me nu) r et
ur n t r ue
_at_Ov er r i de publ i c bool ean onOpt i ons I t e
mS el ec t ed( Me nuI t em i t e m) s wi t c h
( i t e m. get I t e mI d( ) ) c as e R. i d.
addDet a i l s / / Cal l f or add dat a I nt
ent i nt ent new I nt ent ( get Appl i c at i
onCont ex t ( ) , AddUpdat e Det a i l s Ac t i v
i t y . c l as s ) opr at i on 0 s t ar t
Ac t i v i t y For Res ul t ( i nt ent , 1) r
et ur n t r ue r et ur n s uper . onOpt i ons
I t e mS el ec t ed( i t e m)
_at_Ov er r i de pr ot ec t ed voi d onAc t i v i t
y Res ul t ( i nt r eques t Code, i nt r es ul t
Code, I nt ent dat a ) s uper . onAc t i v i t
y Res ul t ( r eques t Code, r es ul t Code, dat
a ) t r y i f ( r eques t Code r es ul t
Code) r ef er s hL ay out ( ) Toas t . ma k
e Tex t ( get Appl i c at i onCont ex t ( ) , "
Res ul t s uc c es s " dat a . get St r i
ngEx t r a ( " ms g" ) , Toas t . L ENGT el s e
St r i ng s t r dat a . get St r i ngEx t r a
( " ms g" ) i f ( Tex t Ut i l s . i s E mpt
y( s t r ) ) Toas t . ma k e Tex t ( get Appl i
c at i onCont ex t ( ) , " e mpt y " , Toas t . L
ENGTH_ SHORT) . s how( ) el s e L og. e( "
Er r or " , s t r ) Toas t . ma k e Tex t ( get
Appl i c at i onCont ex t ( ) , " Er r or "
dat a . get St r i ngEx t r a ( " ms g" ) , Toas
t . L ENGTH_ SHO c at c h ( Ex c ept i on
e) e. pr i nt St ac k Tr ac e( )
publ i c voi d r ef er s hL ay out ( ) i f (
Bui l d. VERSI ON. SDK_ I NT gt 16) t hi s . r
ec r eat e ( ) el s e f i nal I nt ent i nt
ent get I nt ent ( ) i nt ent . addFl ags ( I
nt ent . FL AG_ ACTI VI TY_ NO_ ANI MAT I ON)
t hi s . f i ni s h( ) t hi s . over r i de
Pendi ngTr ans i t i on( 0, 0) t hi s . s t ar
t Ac t i v i t y( i nt ent ) t hi s . over r i
de Pendi ngTr ans i t i on( 0, 0)
I hope you like this article. If you have
followed this tutorial carefully then application
run without any is sue. Write us if there is any
is sue to implement SQLite Database In Android.
Happy Coding