Android學(xué)習(xí)筆記-保存數(shù)據(jù)到SQL數(shù)據(jù)庫中(Saving Data in SQL Databases)
知識點:
1.使用SQL Helper創(chuàng)建數(shù)據(jù)庫
2.數(shù)據(jù)的增刪查改(PRDU:Put、Read、Delete、Update)
背景知識:
上篇文章學(xué)習(xí)了android保存文件,今天學(xué)習(xí)的是保存數(shù)據(jù)到SQL數(shù)據(jù)庫中。相信大家對數(shù)據(jù)庫都不陌生。對于大量重復(fù)的,有特定結(jié)構(gòu)的數(shù)據(jù)的保存,用 SQL數(shù)據(jù)庫 來保存是最理想不過了。
下面將用一個關(guān)于聯(lián)系人的數(shù)據(jù)庫Demo來具體學(xué)習(xí)。
具體知識:
1.定義Contract類
在創(chuàng)建SQL數(shù)據(jù)庫之前,要創(chuàng)建Contract類。那什么是Contract類呢?
Contract Class的定義:
Contract Class,又可以叫做Companion Class。
Android Developer的幫助文檔是這么說的:
< A contract class is a container for constants that define names for URIs,
tables, and columns. The contract class allows you to use the same constants
across all the other classes in the same package. This lets you change a
column name in one place and have it propagate throughout your code.>
Contact 類是定義URI、表、列的名字的容器。這個類允許我們在同一包的不同類下使用相同的常量。
我們在一處修改了列名,同時傳播到我們代碼的每個地方。
package com.example.sqlitetest;
//Contract類
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;
}
}
2.使用SQLHelper創(chuàng)建數(shù)據(jù)庫
就像保存文件在內(nèi)部存儲一樣,Android在私有的應(yīng)用存儲空間存儲我們的數(shù)據(jù)庫,這樣就保證我們的數(shù)據(jù)是安全的。不能被其他應(yīng)用訪問到。
在設(shè)備上存儲的數(shù)據(jù)庫保存在:
/data/data/<package_name>/databases目錄下

為了使用SQLiteOpenHelper,我們需要創(chuàng)建一個重寫了onCreate(),onUpgrade()和onOpen()回調(diào)方法的子類。
3.數(shù)據(jù)的增刪改查
增:傳ContentValue值到insert()方法。
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
db.insert(TABLE_CONTACTS, null, values);
db.close();
刪:delete()方法
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
改:update()方法
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
ew String[] { String.valueOf(contact.getID()) });
查:query()方法
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;
完整DatabaseHelper代碼如下:
package com.example.sqlitetest;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
// 數(shù)據(jù)庫版本
private static final int DATABASE_VERSION = 1;
// 數(shù)據(jù)庫名
private static final String DATABASE_NAME = "contactsManager";
//Contact表名
private static final String TABLE_CONTACTS = "contacts";
//Contact表的列名
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// 創(chuàng)建表
@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);
}
// 更新表
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 刪除舊表
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
//再次創(chuàng)建表
onCreate(db);
}
/**
*增刪改查操作
*/
// 增加新的聯(lián)系人
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// 插入行
db.insert(TABLE_CONTACTS, null, values);
db.close(); // 關(guān)閉數(shù)據(jù)庫的連接
}
// 獲取聯(lián)系人
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;
}
// 獲取所有聯(lián)系人
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
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));
contactList.add(contact);
} while (cursor.moveToNext());
}
return contactList;
}
// 更新單個聯(lián)系人
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());
//更新行
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// 刪除單個聯(lián)系人
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// 獲取聯(lián)系人數(shù)量
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
還有一些代碼不是本次學(xué)習(xí)的重點,就不貼出來了。有需要的留言找我要。
Demo運行效果圖:








相關(guān)文章
基于RecyclerView實現(xiàn)橫向GridView效果
這篇文章主要為大家詳細(xì)介紹了基于RecyclerView實現(xiàn)橫向GridView效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
Android調(diào)用系統(tǒng)圖庫獲取圖片的方法
這篇文章主要為大家詳細(xì)介紹了Android調(diào)用系統(tǒng)圖庫獲取圖片,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-08-08
Android 使用Vitamio打造自己的萬能播放器(4)——本地播放(快捷搜索、數(shù)據(jù)存儲)
本文主要介紹android Vitamio 本地播放功能(快捷搜索,數(shù)據(jù)存儲),這里提供實例代碼和效果圖,有需要的小伙伴可以參考下2016-07-07
超簡單實現(xiàn)Android自定義Toast示例(附源碼)
本篇文章主要介紹了超簡單實現(xiàn)Android自定義Toast示例(附源碼),具有一定的參考價值,有興趣的可以了解一下。2017-02-02
Android自定義Drawable實現(xiàn)圓形和圓角
這篇文章主要為大家詳細(xì)介紹了Android自定義Drawable實現(xiàn)圓形和圓角,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09
新浪微博第三方登錄界面上下拉伸圖片之第三方開源PullToZoomListViewEx(一)
PullZoomView要實現(xiàn)兩類,一類是典型的Android ListView,另外一類是Android 的scroll view。本文先介紹PullZoomView在ListView上的實現(xiàn):PullToZoomListViewEx2015-12-12
Android自定義view實現(xiàn)帶header和footer的Layout
這篇文章主要介紹了Android自定義view實現(xiàn)帶header和footer的Layout,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02
Kotlin協(xié)程Job生命周期結(jié)構(gòu)化并發(fā)詳解
這篇文章主要為大家介紹了Kotlin協(xié)程Job生命周期結(jié)構(gòu)化并發(fā)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12

