0% found this document useful (0 votes)
76 views

Android Sqlite Tutorial - Javatpoint

The document discusses using SQLite as an embedded database on Android devices, including creating a SQLiteOpenHelper class to manage the database and performing CRUD (create, read, update, delete) operations. It provides code examples for creating a Contact class to store contact data, a DatabaseHandler class that extends SQLiteOpenHelper to implement database functionality, and methods to add, get, update, and delete contact records from the database.

Uploaded by

ravichauhanis420
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views

Android Sqlite Tutorial - Javatpoint

The document discusses using SQLite as an embedded database on Android devices, including creating a SQLiteOpenHelper class to manage the database and performing CRUD (create, read, update, delete) operations. It provides code examples for creating a Contact class to store contact data, a DatabaseHandler class that extends SQLiteOpenHelper to implement database functionality, and methods to add, get, update, and delete contact records from the database.

Uploaded by

ravichauhanis420
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Home Android Java Servlet JSP Struts2 Mail API Hibernate Spring

Android SQLite Tutorial


SQLite is an open-source relational database i.e. used to perform database
operations on android devices such as storing, manipulating or retrieving persistent
data from the database.

It is embedded in android bydefault. So, there is no need to perform any database


setup or administration task.

Here, we are going to see the example of sqlite to store and fetch the data. Data is
displayed in the logcat. For displaying data on the spinner or listview, move to the
next page.

SQLiteOpenHelper class provides the functionality to use the SQLite database.

SQLiteOpenHelper class
The android.database.sqlite.SQLiteOpenHelper class is used for database creation
and version management. For performing any database operation, you have to
provide the implementation of onCreate() and onUpgrade() methods of
SQLiteOpenHelper class.

Constructors of SQLiteOpenHelper class

There are two constructors of SQLiteOpenHelper class.

Constructor Description

SQLiteOpenHelper(Context context, String creates an object for creating,


name, SQLiteDatabase.CursorFactory opening and managing the
factory, int version) database.
:
SQLiteOpenHelper(Context context, String creates an object for creating,
name, SQLiteDatabase.CursorFactory opening and managing the
factory, int version, DatabaseErrorHandler database. It specifies the error
errorHandler) handler.

Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:

Method Description

public abstract void called only once when


onCreate(SQLiteDatabase db) database is created for the first
time.

public abstract void called when database needs to


onUpgrade(SQLiteDatabase db, int be upgraded.
oldVersion, int newVersion)

public synchronized void close () closes the database object.

public void onDowngrade(SQLiteDatabase called when database needs to


db, int oldVersion, int newVersion) be downgraded.
:
SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update,
delete, select etc.

Methods of SQLiteDatabase class

There are many methods in SQLiteDatabase class. Some of them are as follows:

Method Description

void execSQL(String sql) executes the sql query not select query.

long insert(String table, inserts a record on the database. The table


String nullColumnHack, specifies the table name, nullColumnHack doesn't
ContentValues values) allow completely null values. If second argument is
null, android will store null values if values are
empty. The third argument specifies the values to
be stored.

int update(String table, updates a row.


ContentValues values,
String whereClause,
String[] whereArgs)

Cursor query(String returns a cursor over the resultset.


table, String[] columns,
String selection, String[]
selectionArgs, String
groupBy, String having,
String orderBy)

Example of android SQLite database

Let's see the simple example of android sqlite database.


:
File: Contact.java

1. package example.javatpoint.com.sqlitetutorial;
2.
3. public class Contact {
4. int _id;
5. String _name;
6. String _phone_number;
7. public Contact(){ }
8. public Contact(int id, String name, String _phone_number){
9. this._id = id;
10. this._name = name;
11. this._phone_number = _phone_number;
12. }
13.
14. public Contact(String name, String _phone_number){
15. this._name = name;
16. this._phone_number = _phone_number;
17. }
18. public int getID(){
19. return this._id;
20. }
21.
22. public void setID(int id){
23. this._id = id;
24. }
25.
26. public String getName(){
27. return this._name;
28. }
29.
:
30. public void setName(String name){
31. this._name = name;
32. }
33.
34. public String getPhoneNumber(){
35. return this._phone_number;
36. }
37.
38. public void setPhoneNumber(String phone_number){
39. this._phone_number = phone_number;
40. }
41. }

File: DatabaseHandler.java

Now, let's create the database handler class that extends SQLiteOpenHelper class
and provides the implementation of its methods.

1. package example.javatpoint.com.sqlitetutorial;
2.
3. import android.content.ContentValues;
4. import android.content.Context;
5. import android.database.Cursor;
6. import android.database.sqlite.SQLiteDatabase;
7. import android.database.sqlite.SQLiteOpenHelper;
8. import java.util.ArrayList;
9. import java.util.List;
10.
11.
12. public class DatabaseHandler extends SQLiteOpenHelper {
13. private static final int DATABASE_VERSION = 1;
:
14. private static final String DATABASE_NAME = "contactsManager";
15. private static final String TABLE_CONTACTS = "contacts";
16. private static final String KEY_ID = "id";
17. private static final String KEY_NAME = "name";
18. private static final String KEY_PH_NO = "phone_number";
19.
20. public DatabaseHandler(Context context) {
21. super(context, DATABASE_NAME, null, DATABASE_VERSION);
22. //3rd argument to be passed is CursorFactory instance
23. }
24.
25. // Creating Tables
26. @Override
27. public void onCreate(SQLiteDatabase db) {
28. String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "
("
29. + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
30. + KEY_PH_NO + " TEXT" + ")";
31. db.execSQL(CREATE_CONTACTS_TABLE);
32. }
33.
34. // Upgrading database
35. @Override
36. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
37. // Drop older table if existed
38. db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
39.
40. // Create tables again
41. onCreate(db);
42. }
43.
:
44. // code to add the new contact
45. void addContact(Contact contact) {
46. SQLiteDatabase db = this.getWritableDatabase();
47.
48. ContentValues values = new ContentValues();
49. values.put(KEY_NAME, contact.getName()); // Contact Name
50. values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
51.
52. // Inserting Row
53. db.insert(TABLE_CONTACTS, null, values);
54. //2nd argument is String containing nullColumnHack
55. db.close(); // Closing database connection
56. }
57.
58. // code to get the single contact
59. Contact getContact(int id) {
60. SQLiteDatabase db = this.getReadableDatabase();
61.
62. Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
63. KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
64. new String[] { String.valueOf(id) }, null, null, null, null);
65. if (cursor != null)
66. cursor.moveToFirst();
67.
68. Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
69. cursor.getString(1), cursor.getString(2));
70. // return contact
71. return contact;
72. }
73.
74. // code to get all contacts in a list view
:
75. public List<Contact> getAllContacts() {
76. List<Contact> contactList = new ArrayList<Contact>();
77. // Select All Query
78. String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
79.
80. SQLiteDatabase db = this.getWritableDatabase();
81. Cursor cursor = db.rawQuery(selectQuery, null);
82.
83. // looping through all rows and adding to list
84. if (cursor.moveToFirst()) {
85. do {
86. Contact contact = new Contact();
87. contact.setID(Integer.parseInt(cursor.getString(0)));
88. contact.setName(cursor.getString(1));
89. contact.setPhoneNumber(cursor.getString(2));
90. // Adding contact to list
91. contactList.add(contact);
92. } while (cursor.moveToNext());
93. }
94.
95. // return contact list
96. return contactList;
97. }
98.
99. // code to update the single contact
100. public int updateContact(Contact contact) {
101. SQLiteDatabase db = this.getWritableDatabase();
102.
103. ContentValues values = new ContentValues();
104. values.put(KEY_NAME, contact.getName());
105. values.put(KEY_PH_NO, contact.getPhoneNumber());
:
106.
107. // updating row
108. return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
109. new String[] { String.valueOf(contact.getID()) });
110. }
111.
112. // Deleting single contact
113. public void deleteContact(Contact contact) {
114. SQLiteDatabase db = this.getWritableDatabase();
115. db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
116. new String[] { String.valueOf(contact.getID()) });
117. db.close();
118. }
119.
120. // Getting contacts Count
121. public int getContactsCount() {
122. String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
123. SQLiteDatabase db = this.getReadableDatabase();
124. Cursor cursor = db.rawQuery(countQuery, null);
125. cursor.close();
126.
127. // return count
128. return cursor.getCount();
129. }
130.
131. }

File: MainActivity.java

1. package example.javatpoint.com.sqlitetutorial;
2.
:
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.util.Log;
6. import java.util.List;
7.
8. public class MainActivity extends AppCompatActivity {
9.
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_main);
14. DatabaseHandler db = new DatabaseHandler(this);
15.
16. // Inserting Contacts
17. Log.d("Insert: ", "Inserting ..");
18. db.addContact(new Contact("Ravi", "9100000000"));
19. db.addContact(new Contact("Srinivas", "9199999999"));
20. db.addContact(new Contact("Tommy", "9522222222"));
21. db.addContact(new Contact("Karthik", "9533333333"));
22.
23. // Reading all contacts
24. Log.d("Reading: ", "Reading all contacts..");
25. List<Contact> contacts = db.getAllContacts();
26.
27. for (Contact cn : contacts) {
28. String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " +
29. cn.getPhoneNumber();
30. // Writing Contacts to log
31. Log.d("Name: ", log);
32. }
33. }
:
34. }

Output:

How to view the data stored in sqlite in android studio?

Follow the following steps to view the database and its data stored in android sqlite:

Open File Explorer.

Go to data directory inside data directory.

Search for your application package name.

Inside your application package go to databases where you will found your
database (contactsManager).

Save your database (contactsManager) anywhere you like.

Download any SqLite browser plugins or tool (in my case DB Browser for
SQLite).

Launch DB Browser for SQLite and open your database (contactsManager).

Go to Browse Data -> select your table (contacts) you will see the data stored.
:
<<Prev Next>>
:
Youtube For Videos Join Our Youtube Channel: Join Now

Feedback

Send your Feedback to [email protected]

Help Others, Please Share

Learn Latest Tutorials

Splunk tutorial SPSS tutorial Swagger tutorial

Splunk SPSS Swagger

T-SQL tutorial Tumblr tutorial React tutorial

Transact-SQL Tumblr ReactJS


:
Regex tutorial

Regex Reinforcement R Programming


Learning

RxJS tutorial

RxJS React Native Python Design


Patterns

Keras tutorial

Python Pillow Python Turtle Keras

Preparation

Aptitude Verbal Ability

Aptitude Reasoning Verbal Ability

Interview Company
Questions Questions
:
Trending Technologies

AWS Tutorial Selenium tutorial

Artificial AWS Selenium


Intelligence

Cloud Computing Hadoop tutorial ReactJS Tutorial

Cloud Computing Hadoop ReactJS

Data Science Angular 7 Blockchain

Git Tutorial DevOps Tutorial

Git Machine Learning DevOps

B.Tech / MCA
:
DBMS tutorial DAA tutorial

DBMS Data Structures DAA

Operating System

Operating System Computer Network Compiler Design

Ethical Hacking

Computer Discrete Ethical Hacking


Organization Mathematics

html tutorial

Computer Graphics Software Web Technology


Engineering

Automata Tutorial

Cyber Security Automata C Programming

C++ tutorial Java tutorial

C++ Java .Net

Python tutorial List of Programs

Python Programs Control System


:
Data Mining Data Warehouse
:

You might also like