Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
HMKCode
Code First!
Objectives:
We will build an App that can store & retrieve books title and author name.
http://hmkcode.com/androidsimplesqlitedatabasetutorial/ 1/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode
/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/androidsimplesqlitedatabasetutorial/ 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.
/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.
http://hmkcode.com/androidsimplesqlitedatabasetutorial/ 3/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode
1. addBook(Book book)
2. getBook(int id)
3. getAllBooks()
4. update(Book book)
5. delete(Book book)
// 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:
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/androidsimplesqlitedatabasetutorial/ 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/androidsimplesqlitedatabasetutorial/ 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 }
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/androidsimplesqlitedatabasetutorial/ 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/androidsimplesqlitedatabasetutorial/ 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/androidsimplesqlitedatabasetutorial/ 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 }
/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/androidsimplesqlitedatabasetutorial/ 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 }
Log function Log.d() used within the addBook(), getBook()…etc. will log database operations on LogCat Eclipse
(ADT) window.
http://hmkcode.com/androidsimplesqlitedatabasetutorial/ 10/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode
LogCat view
http://hmkcode.com/androidsimplesqlitedatabasetutorial/ 11/12
08/08/2016 Android | Simple SQLite Database Tutorial | HMKCode
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/] .
Ferdinando Cecchini
September 24, 2013 at 11:30 am
http://hmkcode.com/androidsimplesqlitedatabasetutorial/ 12/12