Android SQLite教程
SQLite 是一個 開源的關系型數據庫 即用于在Android設備上執行數據庫操作,如存儲、操作或檢索持久數據。愛掏網 - it200.com
它被默認嵌入到Android中,因此無需執行任何數據庫設置或管理任務。愛掏網 - it200.com
在這里,我們將看到使用SQLite存儲和獲取數據的示例。愛掏網 - it200.com數據顯示在logcat中。愛掏網 - it200.com要在下一個頁面上顯示數據在下拉列表或列表視圖上,請轉到下一頁。愛掏網 - it200.com
SQLiteOpenHelper 類提供了使用SQLite數據庫的功能。愛掏網 - it200.com
android.database.sqlite.SQLiteOpenHelper類用于數據庫的創建和版本管理。愛掏網 - it200.com要執行任何數據庫操作,您必須提供SQLiteOpenHelper類的 onCreate() 和 onUpgrade() 方法的實現。愛掏網 - it200.com
SQLiteOpenHelper類的構造函數
SQLiteOpenHelper類有兩個構造函數。愛掏網 - it200.com
構造函數 | 描述 |
---|---|
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) | 創建、打開和管理數據庫的對象。愛掏網 - it200.com |
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) | 創建、打開和管理數據庫的對象。愛掏網 - it200.com它指定了錯誤處理程序。愛掏網 - it200.com |
SQLiteOpenHelper類的方法
SQLiteOpenHelper類中有許多方法。愛掏網 - it200.com以下是其中一些:
方法 | 描述 |
---|---|
public abstract void onCreate(SQLiteDatabase db) | 在數據庫第一次創建時調用,僅調用一次。愛掏網 - it200.com |
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) | 在數據庫需要升級時調用。愛掏網 - it200.com |
public synchronized void close () | 關閉數據庫對象。愛掏網 - it200.com |
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) | 在數據庫需要降級時調用。愛掏網 - it200.com |
SQLiteDatabase class
它包含了對sqlite數據庫執行的方法,例如創建、更新、刪除、選擇等。愛掏網 - it200.com
SQLiteDatabase類的方法
SQLiteDatabase類中有許多方法。愛掏網 - it200.com其中一些如下:
方法 | 描述 |
---|---|
void execSQL(String sql) | 執行非選擇查詢的sql語句。愛掏網 - it200.com |
long insert(String table, String nullColumnHack, ContentValues values) | 在數據庫上插入一條記錄。愛掏網 - it200.comtable指定表名,nullColumnHack不允許完全為空的值。愛掏網 - it200.com如果第二個參數為空,android將在values為空時保存空值。愛掏網 - it200.com第三個參數指定要存儲的值。愛掏網 - it200.com |
int update(String table, ContentValues values, String whereClause, String[] whereArgs) | 更新一行。愛掏網 - it200.com |
Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) | 返回結果集的游標。愛掏網 - it200.com |
Android SQLite數據庫示例
讓我們看一個簡單的Android SQLite數據庫示例。愛掏網 - it200.com
package example.javatpoint.com.sqlitetutorial;
public class Contact {
int _id;
String _name;
String _phone_number;
public Contact(){ }
public Contact(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
public Contact(String name, String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
public int getID(){
return this._id;
}
public void setID(int id){
this._id = id;
}
public String getName(){
return this._name;
}
public void setName(String name){
this._name = name;
}
public String getPhoneNumber(){
return this._phone_number;
}
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
現在,讓我們創建一個擴展SQLiteOpenHelper類并提供其方法實現的數據庫處理程序類。愛掏網 - it200.com
package example.javatpoint.com.sqlitetutorial;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactsManager";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// code to add the new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
//2nd argument is String containing nullColumnHack
db.close(); // Closing database connection
}
// code to get the single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// code to get all contacts in a list view
public List getAllContacts() {
List contactList = new ArrayList();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// code to update the single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
package example.javatpoint.com.sqlitetutorial;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "9100000000"));
db.addContact(new Contact("Srinivas", "9199999999"));
db.addContact(new Contact("Tommy", "9522222222"));
db.addContact(new Contact("Karthik", "9533333333"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
輸出:
如何在Android Studio中查看存儲在SQLite中的數據?
按照以下步驟查看存儲在Android SQLite中的數據庫及其數據:
- 打開文件瀏覽器。愛掏網 - it200.com
- 進入data目錄下的data目錄。愛掏網 - it200.com
- 搜索您的應用程序包名稱。愛掏網 - it200.com
- 在您的應用程序包中進入databases目錄,您將找到您的數據庫(contactsManager)。愛掏網 - it200.com
- 將您的數據庫(contactsManager)保存在任何您喜歡的位置。愛掏網 - it200.com
- 下載任何SqLite瀏覽器插件或工具(在我的情況下是DB Browser for SQLite)。愛掏網 - it200.com
- 啟動DB Browser for SQLite并打開您的數據庫(contactsManager)。愛掏網 - it200.com
- 轉到瀏覽數據 -> 選擇您的表格(contacts),您將看到存儲的數據。愛掏網 - it200.com