Android學(xué)習(xí)筆記-保存數(shù)據(jù)到SQL數(shù)據(jù)庫(kù)中(Saving Data in SQL Databases)
知識(shí)點(diǎn):
1.使用SQL Helper創(chuàng)建數(shù)據(jù)庫(kù)
2.數(shù)據(jù)的增刪查改(PRDU:Put、Read、Delete、Update)
背景知識(shí):
上篇文章學(xué)習(xí)了android保存文件,今天學(xué)習(xí)的是保存數(shù)據(jù)到SQL數(shù)據(jù)庫(kù)中。相信大家對(duì)數(shù)據(jù)庫(kù)都不陌生。對(duì)于大量重復(fù)的,有特定結(jié)構(gòu)的數(shù)據(jù)的保存,用 SQL數(shù)據(jù)庫(kù) 來(lái)保存是最理想不過(guò)了。
下面將用一個(gè)關(guān)于聯(lián)系人的數(shù)據(jù)庫(kù)Demo來(lái)具體學(xué)習(xí)。
具體知識(shí):
1.定義Contract類
在創(chuàng)建SQL數(shù)據(jù)庫(kù)之前,要?jiǎng)?chuàng)建Contract類。那什么是Contract類呢?
Contract Class的定義:
Contract Class,又可以叫做Companion Class。
Android Developer的幫助文檔是這么說(shuō)的:
< 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、表、列的名字的容器。這個(gè)類允許我們?cè)谕话牟煌愊率褂孟嗤某A俊?br /> 我們?cè)谝惶幮薷牧肆忻瑫r(shí)傳播到我們代碼的每個(gè)地方。
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ù)庫(kù)
就像保存文件在內(nèi)部存儲(chǔ)一樣,Android在私有的應(yīng)用存儲(chǔ)空間存儲(chǔ)我們的數(shù)據(jù)庫(kù),這樣就保證我們的數(shù)據(jù)是安全的。不能被其他應(yīng)用訪問(wèn)到。
在設(shè)備上存儲(chǔ)的數(shù)據(jù)庫(kù)保存在:
/data/data/<package_name>/databases目錄下
為了使用SQLiteOpenHelper,我們需要?jiǎng)?chuàng)建一個(gè)重寫(xiě)了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ù)庫(kù)版本
private static final int DATABASE_VERSION = 1;
// 數(shù)據(jù)庫(kù)名
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ù)庫(kù)的連接
}
// 獲取聯(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;
}
// 更新單個(gè)聯(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()) });
}
// 刪除單個(gè)聯(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í)的重點(diǎn),就不貼出來(lái)了。有需要的留言找我要。
Demo運(yùn)行效果圖:
相關(guān)文章
Android模擬器實(shí)現(xiàn)手機(jī)添加文件到sd卡的方法
這篇文章主要介紹了Android模擬器實(shí)現(xiàn)手機(jī)添加文件到sd卡的方法,詳細(xì)分析了Android模擬器添加文件到sd卡的步驟與相關(guān)技巧,需要的朋友可以參考下2016-06-06Android中利用C++處理Bitmap對(duì)象的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇Android中利用C++處理Bitmap對(duì)象的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-03-03Android開(kāi)發(fā)兩個(gè)activity之間傳值示例詳解
這篇文章主要為大家介紹了Android開(kāi)發(fā)兩個(gè)activity之間傳值示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07超簡(jiǎn)單Android集成華為HMS Scankit 掃碼SDK實(shí)現(xiàn)掃一掃二維碼
這篇文章主要介紹了超簡(jiǎn)單Android集成華為HMS Scankit 掃碼SDK實(shí)現(xiàn)掃一掃二維碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03Android 如何攔截用戶頻繁操作(點(diǎn)擊事件)
本文主要介紹了Android 如何攔截用戶頻繁操作,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08Android動(dòng)畫(huà)之逐幀動(dòng)畫(huà)(Frame Animation)實(shí)例詳解
這篇文章主要介紹了Android動(dòng)畫(huà)之逐幀動(dòng)畫(huà)(Frame Animation),結(jié)合實(shí)例形式較為詳細(xì)的分析了逐幀動(dòng)畫(huà)的原理,注意事項(xiàng)與相關(guān)使用技巧,需要的朋友可以參考下2016-01-01