編輯:關於 Android 程式設計
Android 提供了多種數據存儲方式。少量數據用 SharedPreferences 或文件存儲即可;但當需要讀寫大量數據時,就得用上數據庫了。Android 內置了 SQLite,這是一個真正的輕量級數據庫——沒有後台進程,整個數據庫就對應一個文件,配合 Android 提供的豐富 API,使用起來相當方便。
Android 用 SQLiteDatabase 對象來管理數據庫,它提供了創建、刪除、執行 SQL 以及各類數據庫管理任務的方法。
SQLiteDatabase 提供了以下靜態方法來打開文件對應的數據庫:
SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags):打開 path 文件代表的數據庫;拿到 SQLiteDatabase 對象後,就可以調用下列方法進行操作:
這些方法本意是幫開發者更「簡便」地增刪改查,但其實它們都能用 SQL 語句完成。與其去記那一長串參數,不如把時間花在掌握 SQL 上。
上述查詢方法都會返回一個 Cursor 接口,它提供對查詢結果集的隨機讀寫訪問,並提供以下方法移動記錄指針:
移動到指定行後,就能調用 getXXX() 系列方法取出各列數據。
創建數據庫:
// 判斷數據庫文件所在文件夾是否存在,不存在則創建
String mPath = Environment.getExternalStorageDirectory() + "/db/";
File file = new File(mPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
// 使用靜態方法打開數據庫(不存在則創建),第二個參數為 Cursor 工廠,null 表示默認
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(mPath + "blog.db", null);
創建表:
// 執行創建表 SQL,創建名為 blog_info 的表 String createSql = "create table blog_info(blog_id integer primary key, blog_name varchar(255), blog_link varchar(255))"; database.execSQL(createSql);
注意:數據庫建在 SD 卡中,需要加上寫入 SD 卡的權限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
建好數據庫和表後,就能管理表中數據了。既可直接用 execSQL() 執行 SQL,也可用 Android 封裝好的增刪改查方法。
insert(String table, String nullColumnHack, ContentValues values):
table:目標表名;
nullColumnHack:當 values 為空時,用來強制插入 null 的列名;
values:一行記錄的數據。
插入參數用 ContentValues,它類似 Map,通過 put(String key, XXX value) 存入,key 為列名。
ContentValues contentValues = new ContentValues();
contentValues.put("blog_name", "Airsaid");
contentValues.put("blog_link", "https://blog.csdn.net/airsaid");
// line 為新添加的行號,出錯時返回 -1
long line = mDatabase.insert("blog_info", null, contentValues);
delete(String table, String whereClause, String[] whereArgs):
table:目標表名;
whereClause:滿足該條件的記錄會被刪除;
whereArgs:為 whereClause 傳入參數。
int num = mDatabase.delete("blog_info", "blog_name like ?", new String[]{"Airsaid"});
Toast.makeText(this, "一共刪除了:" + num + "條數據", Toast.LENGTH_SHORT).show();
update(String table, ContentValues values, String whereClause, String[] whereArgs):
table:目標表名;
values:想更新的數據;
whereClause:滿足條件的數據會被更新;
whereArgs:為 whereClause 傳入參數。
ContentValues contentValues = new ContentValues();
contentValues.put("blog_name", "周游");
int num = mDatabase.update("blog_info", contentValues, "_id > ?", new String[]{"5"});
query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit):
distinct:是否去除重複記錄;
table:目標表名;
columns:要查詢的列名;
selection:查詢條件;
selectionArgs:占位符參數;
groupBy:分組;
having:對分組進行過濾/排序;
orderBy:排序;
limit:分頁。
由於查詢條件多變,query() 的參數實在偏長,寫查詢時不妨直接用 rawQuery()。
下面做個例子:用戶分別輸入博客名和鏈接,點擊插入後存入數據庫,並用列表展示。
布局:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.airsaid.sqlitedemo.MainActivity">
<EditText
android:id="@+id/edt_blog_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<EditText
android:id="@+id/edt_blog_link"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="insert"
android:text="插入數據" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
</LinearLayout>
代碼:
public class MainActivity extends AppCompatActivity {
private String mPath = Environment.getExternalStorageDirectory() + "/db/";
private static final String DB_NAME = "blog.db";
private EditText mEdtName;
private EditText mEdtLink;
private ListView mListView;
private SQLiteDatabase mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEdtName = (EditText) findViewById(R.id.edt_blog_name);
mEdtLink = (EditText) findViewById(R.id.edt_blog_link);
mListView = (ListView) findViewById(R.id.listView);
File file = new File(mPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
mDatabase = SQLiteDatabase.openOrCreateDatabase(mPath + DB_NAME, null);
String createSql = "create table blog_info(_id integer primary key, blog_name varchar(255), blog_link varchar(255))";
mDatabase.execSQL(createSql);
}
/** 插入數據 */
public void insert(View v) {
String name = mEdtName.getText().toString();
String link = mEdtLink.getText().toString();
mDatabase.execSQL("insert into blog_info values(null, ?, ?)", new String[]{name, link});
Cursor cursor = mDatabase.rawQuery("select * from blog_info", null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item_listview_blog, cursor, new String[]{"blog_name", "blog_link"}, new int[]{R.id.txt_name, R.id.txt_link}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
mListView.setAdapter(adapter);
}
}
Item 布局:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/txt_name"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1" />
<TextView
android:id="@+id/txt_link"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1" />
</LinearLayout>
數據庫操作離不開事務,SQLiteDatabase 提供了以下方法:
beginTransaction():開始事務;
endTransaction():結束事務;
inTransaction():判斷當前是否處於事務中。
調用 endTransaction() 時,究竟提交還是回滾,取決於是否調用了 setTransactionSuccessful() 設置事務標志——設置了且事務成功則提交,否則回滾。
真實項目中,很少直接用 SQLiteDatabase 打開數據庫,而是繼承 Android 提供的 SQLiteOpenHelper 抽象類。它是一個輔助類,用來幫助建立和管理數據庫。我們只需繼承它並實現兩個抽象方法:
onCreate(SQLiteDatabase db):初次生成數據庫時調用,用於創建表結構;
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):數據庫版本更新時調用。
繼承 SQLiteOpenHelper,在 onCreate 中創建表:
public class MyDatabaseHelper extends SQLiteOpenHelper {
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table dict(_id integer primary key autoincrement, word, detail)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}
布局分別為單詞輸入框和釋義輸入框,輸入後點擊保存,用戶再輸入要查詢的生詞,點擊查詢並以 Dialog 展示結果。添加生詞:
public void add(View v) {
String word = mEdtWord.getText().toString();
String detail = mEdtDetail.getText().toString();
if (TextUtils.isEmpty(word) || TextUtils.isEmpty(detail)) {
Toast.makeText(this, "輸入的數據不能為空", Toast.LENGTH_SHORT).show();
return;
}
SQLiteDatabase database = mDb.getReadableDatabase();
database.execSQL("insert into dict values(null, ? , ?)", new String[]{word, detail});
Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
}
這裡通過 getReadableDatabase() 拿到 SQLiteDatabase 對象。需要注意的是:getReadableDatabase() 會先以讀寫方式打開,若磁盤空間已滿則打開失敗,再嘗試只讀方式;而 getWritableDatabase() 若磁盤空間已滿,打開時會直接出錯。
查詢:
public void seek(View v) {
String dict = mEdtInput.getText().toString();
SQLiteDatabase database = mDb.getReadableDatabase();
Cursor cursor = database.rawQuery("select * from dict where word like ? or detail like ?", new String[]{"%" + dict + "%", "%" + dict + "%"});
List<String> dicts = new ArrayList<>();
while (cursor.moveToNext()) {
String word = cursor.getString(1);
String detail = cursor.getString(2);
dicts.add("生詞:" + word + " 解釋:" + detail);
}
showData(dicts);
}
展示結果:
private void showData(List<String> dicts) {
if (dicts.size() < 1) {
Toast.makeText(this, "沒有找到該生詞數據", Toast.LENGTH_SHORT).show();
return;
}
new AlertDialog.Builder(this)
.setTitle("查詢出來的單詞結果")
.setItems(dicts.toArray(new String[dicts.size()]), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
運行結果:

Android 資料庫實戰筆記(二):建表語句與 LitePal 快速上手
上一篇我們把 SQLite 的常用命令摸了一遍,不過那些操作都是在命令行裡完成的。數據庫終究要回到程式碼裡才有價值,單獨對一個 .db 檔增刪改查,練習意義大於實用意義。
Android 學習筆記二十:Toast 吐司、Notification 通知與 PopupWindow 彈出視窗
Toast 吐司 Toast 是我們日常開發中經常使用的元件。它是 Android 系統用來顯示訊息的一種機制,與 Dialog 不同,Toast 不會取得焦點,通常在顯
Android SurfaceView 抽獎轉盤全流程實作
SurfaceView 與一般 View 的差異 SurfaceView 適合需要高頻率重繪的場景,例如遊戲或動畫。它與一般 View 最大的不同在於繪製可發生在獨立執行
ButterKnife 源碼解析:編譯期生成程式碼如何取代 findViewById
身為 Android 開發者,大概沒人沒聽過 ButterKnife。它把 findViewById 與 setOnClickListener 這類樣板收進注解裡,開發效