Sei sulla pagina 1di 12

08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode

HMKCode
Code First!

Android | Simple SQLite Database Tutorial


Android SQLite database is an integral part “built-in”
component. Any databases you create will be
accessible by name to any class in the application,
but not outside the application. Here we will see how
to use SQLite API to perform database common
operations.

Objectives:

How to start using SQLite API?


How to create new database & database tables?
How to perform CRUD “Create, Read, Update and Delete” operations?

Environment & Tools:

Android Developer Tools (ADT) (or Eclipse + ADT plugin)


AVD Nexus S Android 4.3 “emulator”
Min SDK 8

What we are building here?

We will build an App that can store & retrieve books title and author name.

( 1 ) Create Android Application

File >> New >> Android Application


Enter App name: SQLite App
Enter Project name: android-sqlite
Pakcage: com.hmkcode.android

http://hmkcode.com/android­simple­sqlite­database­tutorial/ 1/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode

Keep other defualt selections, click Next until you reach Finish

( 2 ) Data Model Design “Table Structure”

We want to create the following:

One Database instance: “BookDB“.


One Table: “books” with three columns id, title & author

( 3 ) Object Model “Book.java”

Create one Java bean class: Book.java

/src/com/hmkcode/android/model/Book.java

1 package com.hmkcode.android.model; ?
2  
3 public class Book {
4  
5     private int id;
6     private String title;
7     private String author;
8  
9     public Book(){}
10  
11     public Book(String title, String author) {
12         super();
13         this.title = title;
14         this.author = author;
15     }
16  
17     //getters & setters
18  
19     @Override
20     public String toString() {
21         return "Book [id=" + id + ", title=" + title + ", author=" + author
22                 + "]";
23     }
24 }

( 4 ) extends SQLiteOpenHelper

http://hmkcode.com/android­simple­sqlite­database­tutorial/ 2/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode

The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override
the onCreate() method, in which you can execute a SQLite command to create tables in the database.

This is the main step.

Create a new class MySQLiteHelper extends SQLiteOpenHelper.


MySQLiteHelper constructor must call the super class constructor.
Override onCreate() method to create the table(s)
Override onUpgrade() to drop old tables and create new ones.

/src/com/hmkcode/android/sqlite/MySQLiteHelper.java

1 package com.hmkcode.android.sqlite; ?
2  
3 import android.content.Context;
4 import android.database.sqlite.SQLiteDatabase;
5 import android.database.sqlite.SQLiteOpenHelper;
6  
7 public class MySQLiteHelper extends SQLiteOpenHelper {
8  
9     // Database Version
10     private static final int DATABASE_VERSION = 1;
11     // Database Name
12     private static final String DATABASE_NAME = "BookDB";
13  
14     public MySQLiteHelper(Context context) {
15         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
16     }
17  
18     @Override
19     public void onCreate(SQLiteDatabase db) {
20         // SQL statement to create book table
21         String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
22                 "id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
23                 "title TEXT, "+
24                 "author TEXT )";
25  
26         // create books table
27         db.execSQL(CREATE_BOOK_TABLE);
28     }
29  
30     @Override
31     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
32         // Drop older books table if existed
33         db.execSQL("DROP TABLE IF EXISTS books");
34  
35         // create fresh books table
36         this.onCreate(db);
37     }
38  
39 }

This class MySQLiteHelper will just create for us Database “BookDB” with one empty table “books“.
Next, we will create methods to help us populate “insert”, read “select”, update and delete book(s) from
this table.

( 5 ) Add, Get, Update & Delete a Book

http://hmkcode.com/android­simple­sqlite­database­tutorial/ 3/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode

In the same 砖le “MySQLiteHelper.java” we will add 5 methods

1. addBook(Book book)
2. getBook(int id)
3. getAllBooks()
4. update(Book book)
5. delete(Book book)

Some static constants 

De砖ne static constants for table & columns names;

    // Books table name
    private static final String TABLE_BOOKS = "books";

    // Books Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_AUTHOR = "author";

    private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR};

1. addBook(Book book)

Notice:

ConentValues this class is used to store a set of values.


Log.d() just for logging, so we can see the result later on LogCat when we run the App.

1 public void addBook(Book book){ ?
2                 //for logging
3         Log.d("addBook", book.toString()); 
4  
5         // 1. get reference to writable DB
6         SQLiteDatabase db = this.getWritableDatabase();
7  
8         // 2. create ContentValues to add key "column"/value
9         ContentValues values = new ContentValues();
10         values.put(KEY_TITLE, book.getTitle()); // get title 
11         values.put(KEY_AUTHOR, book.getAuthor()); // get author
12  
13         // 3. insert
14         db.insert(TABLE_BOOKS, // table
15                 null, //nullColumnHack
16                 values); // key/value ‐> keys = column names/ values = column values
17  
18         // 4. close
19         db.close(); 
20     }
http://hmkcode.com/android­simple­sqlite­database­tutorial/ 4/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode
20     }

2. getBook(int id)

1 public Book getBook(int id){ ?
2  
3     // 1. get reference to readable DB
4     SQLiteDatabase db = this.getReadableDatabase();
5  
6     // 2. build query
7     Cursor cursor = 
8             db.query(TABLE_BOOKS, // a. table
9             COLUMNS, // b. column names
10             " id = ?", // c. selections 
11             new String[] { String.valueOf(id) }, // d. selections args
12             null, // e. group by
13             null, // f. having
14             null, // g. order by
15             null); // h. limit
16  
17     // 3. if we got results get the first one
18     if (cursor != null)
19         cursor.moveToFirst();
20  
21     // 4. build book object
22     Book book = new Book();
23     book.setId(Integer.parseInt(cursor.getString(0)));
24     book.setTitle(cursor.getString(1));
25     book.setAuthor(cursor.getString(2));
26  
27     //log 
28 Log.d("getBook("+id+")", book.toString());
29  
30     // 5. return book
31     return book;
32 }

3. getAllBooks()

1 public List<Book> getAllBooks() { ?
2        List<Book> books = new LinkedList<Book>();
3  
4        // 1. build the query
5        String query = "SELECT  * FROM " + TABLE_BOOKS;
6  
7        // 2. get reference to writable DB
8        SQLiteDatabase db = this.getWritableDatabase();
9        Cursor cursor = db.rawQuery(query, null);
10  
11        // 3. go over each row, build book and add it to list
12        Book book = null;
13        if (cursor.moveToFirst()) {
14            do {
15                book = new Book();
16                book.setId(Integer.parseInt(cursor.getString(0)));
17                book.setTitle(cursor.getString(1));
18                book.setAuthor(cursor.getString(2));
19  
20                // Add book to books
21                books.add(book);
22            } while (cursor.moveToNext());
23        }
24  
25        Log.d("getAllBooks()", books.toString());
http://hmkcode.com/android­simple­sqlite­database­tutorial/ 5/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode
25        Log.d("getAllBooks()", books.toString());
26  
27        // return books
28        return books;
29    }

4. update(Book book)

1 public int updateBook(Book book) { ?
2  
3     // 1. get reference to writable DB
4     SQLiteDatabase db = this.getWritableDatabase();
5  
6     // 2. create ContentValues to add key "column"/value
7     ContentValues values = new ContentValues();
8     values.put("title", book.getTitle()); // get title 
9     values.put("author", book.getAuthor()); // get author
10  
11     // 3. updating row
12     int i = db.update(TABLE_BOOKS, //table
13             values, // column/value
14             KEY_ID+" = ?", // selections
15             new String[] { String.valueOf(book.getId()) }); //selection args
16  
17     // 4. close
18     db.close();
19  
20     return i;
21  
22 }

5. delete(Book book)

1 public void deleteBook(Book book) { ?
2  
3         // 1. get reference to writable DB
4         SQLiteDatabase db = this.getWritableDatabase();
5  
6         // 2. delete
7         db.delete(TABLE_BOOKS, //table name
8                 KEY_ID+" = ?",  // selections
9                 new String[] { String.valueOf(book.getId()) }); //selections args
10  
11         // 3. close
12         db.close();
13  
14         //log
15     Log.d("deleteBook", book.toString());
16  
17     }

Complete MySQLiteHelper.java Code:

1 package com.hmkcode.android.sqlite; ?
2  
3 import java.util.LinkedList;
4 import java.util.List;
5  
6 import com.hmkcode.android.model.Book;
7  
8 import android.content.ContentValues;
9 import android.content.Context;
10 import android.database.Cursor;
http://hmkcode.com/android­simple­sqlite­database­tutorial/ 6/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode
10 import android.database.Cursor;
11 import android.database.sqlite.SQLiteDatabase;
12 import android.database.sqlite.SQLiteOpenHelper;
13 import android.util.Log;
14  
15 public class MySQLiteHelper extends SQLiteOpenHelper {
16  
17     // Database Version
18     private static final int DATABASE_VERSION = 1;
19     // Database Name
20     private static final String DATABASE_NAME = "BookDB";
21  
22     public MySQLiteHelper(Context context) {
23         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
24     }
25  
26     @Override
27     public void onCreate(SQLiteDatabase db) {
28         // SQL statement to create book table
29         String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
30                 "id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
31                 "title TEXT, "+
32                 "author TEXT )";
33  
34         // create books table
35         db.execSQL(CREATE_BOOK_TABLE);
36     }
37  
38     @Override
39     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
40         // Drop older books table if existed
41         db.execSQL("DROP TABLE IF EXISTS books");
42  
43         // create fresh books table
44         this.onCreate(db);
45     }
46     //‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
47  
48     /**
49      * CRUD operations (create "add", read "get", update, delete) book + get all books + delete
50      */
51  
52     // Books table name
53     private static final String TABLE_BOOKS = "books";
54  
55     // Books Table Columns names
56     private static final String KEY_ID = "id";
57     private static final String KEY_TITLE = "title";
58     private static final String KEY_AUTHOR = "author";
59  
60     private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR};
61  
62     public void addBook(Book book){
63         Log.d("addBook", book.toString());
64         // 1. get reference to writable DB
65         SQLiteDatabase db = this.getWritableDatabase();
66  
67         // 2. create ContentValues to add key "column"/value
68         ContentValues values = new ContentValues();
69         values.put(KEY_TITLE, book.getTitle()); // get title 
70         values.put(KEY_AUTHOR, book.getAuthor()); // get author
71  
72         // 3. insert
73         db.insert(TABLE_BOOKS, // table
74                 null, //nullColumnHack
75                 values); // key/value ‐> keys = column names/ values = column values
76  
77         // 4. close
78         db.close(); 
79     }
http://hmkcode.com/android­simple­sqlite­database­tutorial/ 7/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode
79     }
80  
81     public Book getBook(int id){
82  
83         // 1. get reference to readable DB
84         SQLiteDatabase db = this.getReadableDatabase();
85  
86         // 2. build query
87         Cursor cursor = 
88                 db.query(TABLE_BOOKS, // a. table
89                 COLUMNS, // b. column names
90                 " id = ?", // c. selections 
91                 new String[] { String.valueOf(id) }, // d. selections args
92                 null, // e. group by
93                 null, // f. having
94                 null, // g. order by
95                 null); // h. limit
96  
97         // 3. if we got results get the first one
98         if (cursor != null)
99             cursor.moveToFirst();
100  
101         // 4. build book object
102         Book book = new Book();
103         book.setId(Integer.parseInt(cursor.getString(0)));
104         book.setTitle(cursor.getString(1));
105         book.setAuthor(cursor.getString(2));
106  
107         Log.d("getBook("+id+")", book.toString());
108  
109         // 5. return book
110         return book;
111     }
112  
113     // Get All Books
114     public List<Book> getAllBooks() {
115         List<Book> books = new LinkedList<Book>();
116  
117         // 1. build the query
118         String query = "SELECT  * FROM " + TABLE_BOOKS;
119  
120         // 2. get reference to writable DB
121         SQLiteDatabase db = this.getWritableDatabase();
122         Cursor cursor = db.rawQuery(query, null);
123  
124         // 3. go over each row, build book and add it to list
125         Book book = null;
126         if (cursor.moveToFirst()) {
127             do {
128                 book = new Book();
129                 book.setId(Integer.parseInt(cursor.getString(0)));
130                 book.setTitle(cursor.getString(1));
131                 book.setAuthor(cursor.getString(2));
132  
133                 // Add book to books
134                 books.add(book);
135             } while (cursor.moveToNext());
136         }
137  
138         Log.d("getAllBooks()", books.toString());
139  
140         // return books
141         return books;
142     }
143  
144      // Updating single book
145     public int updateBook(Book book) {
146  
147         // 1. get reference to writable DB
148         SQLiteDatabase db = this.getWritableDatabase();
http://hmkcode.com/android­simple­sqlite­database­tutorial/ 8/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode
148         SQLiteDatabase db = this.getWritableDatabase();
149  
150         // 2. create ContentValues to add key "column"/value
151         ContentValues values = new ContentValues();
152         values.put("title", book.getTitle()); // get title 
153         values.put("author", book.getAuthor()); // get author
154  
155         // 3. updating row
156         int i = db.update(TABLE_BOOKS, //table
157                 values, // column/value
158                 KEY_ID+" = ?", // selections
159                 new String[] { String.valueOf(book.getId()) }); //selection args
160  
161         // 4. close
162         db.close();
163  
164         return i;
165  
166     }
167  
168     // Deleting single book
169     public void deleteBook(Book book) {
170  
171         // 1. get reference to writable DB
172         SQLiteDatabase db = this.getWritableDatabase();
173  
174         // 2. delete
175         db.delete(TABLE_BOOKS,
176                 KEY_ID+" = ?",
177                 new String[] { String.valueOf(book.getId()) });
178  
179         // 3. close
180         db.close();
181  
182         Log.d("deleteBook", book.toString());
183  
184     }
185 }

( 6 ) Using MySQLiteHelper in Activity

/src/com/hmkcode/android/MainActivity.java

1 package com.hmkcode.android; ?
2  
3 import java.util.List;
4 import com.hmkcode.android.model.Book;
5 import com.hmkcode.android.sqlite.MySQLiteHelper;
6 import android.os.Bundle;
7 import android.app.Activity;
8  
9 public class MainActivity extends Activity {
10  
11     @Override
12     protected void onCreate(Bundle savedInstanceState) {
13         super.onCreate(savedInstanceState);
14         setContentView(R.layout.activity_main);
15  
16         MySQLiteHelper db = new MySQLiteHelper(this);
17  
18         /**
19          * CRUD Operations
20          * */
21         // add Books

22         db.addBook(new Book("Android Application Development Cookbook", "Wei Meng Lee"));   
http://hmkcode.com/android­simple­sqlite­database­tutorial/ 9/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode
22         db.addBook(new Book("Android Application Development Cookbook", "Wei Meng Lee"));   
23         db.addBook(new Book("Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and 
24         db.addBook(new Book("Learn Android App Development", "Wallace Jackson"));
25  
26         // get all books
27         List<Book> list = db.getAllBooks();
28  
29         // delete one book
30         db.deleteBook(list.get(0));
31  
32         // get all books
33         db.getAllBooks();
34  
35     }
36  
37 }

Deploy the App on the emulator and run it.


Look for the results in LogCat!

( 7 ) Where to See the Results? LogCat!

Log function Log.d() used within the addBook(), getBook()…etc. will log database operations on LogCat Eclipse
(ADT) window.

If you don’t see LogCat window, you need to add it.


go to Window >> Show View >> Others… (on Show View window) Android >> LogCat

http://hmkcode.com/android­simple­sqlite­database­tutorial/ 10/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode

LogCat view

http://hmkcode.com/android­simple­sqlite­database­tutorial/ 11/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode

Source Code @ GitHub

Related posts from Android Tutorial

Android | SQLite Database Debugging From a Remote Shell

Android – Creating a Navigation Drawer

Android | Send “POST” JSON Data to Server

This entry was posted in Android and tagged android, crud, sql, sqlite, SQLiteDatabase on September 21, 2013
[http://hmkcode.com/android-simple-sqlite-database-tutorial/] .

One thought on “Android | Simple SQLite Database Tutorial”

Ferdinando Cecchini
September 24, 2013 at 11:30 am

Very interesting post!


I’ve a question: is there any method to save the SQLite db on a remote server (for backup purpose) or import
the data from a remote server instead of insert records directly from the application?
Thanks

Comments are closed.

Copyright © 2013 hmkcode.com All Rights Reserved.

http://hmkcode.com/android­simple­sqlite­database­tutorial/ 12/12

Potrebbero piacerti anche