編輯:關於 Android 程式設計
先把兩個容易混淆的觀念釐清。用 new File("hah.txt") 只是建立了一個指向該路徑的物件,檔案可能已存在也可能不存在,並不會被真的建出來;只有當有輸出流對它執行寫入時,檔案才會落地。
另外,所謂「游標」(Cursor)可以想成指向結果集的指標。資料庫內部靠索引快速定位某一列,Cursor 透過上下的移動(moveToNext())逐列取值。
在 Android 使用 SQLite,標準做法是自訂一個類別繼承 SQLiteOpenHelper。這個類別沒有提供無參數建構子,所以子類必須顯式呼叫父類建構子。
package com.test.sqllitedemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBOpenHelper extends SQLiteOpenHelper {
// 子類建構子的參數不必與父類完全一致
public MyDBOpenHelper(Context context) {
/**
* @param context 上下文
* @param name 資料庫檔案名稱
* @param factory 用來建立游標的工廠,null 代表使用預設
* @param version 資料庫版本號,從 1 開始,用於升級
* 副檔名不固定,寫成 .db 只是方便辨識
*/
super(context, "test.db", null, 1);
}
@Override
// 資料庫第一次被建立時才會執行
public void onCreate(SQLiteDatabase db) {
}
@Override
// 版本號變動時執行
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
要特別注意:單純 new 一個 Helper 並不會建立資料庫,必須呼叫 getWritableDatabase() 或 getReadableDatabase() 才會真正落地。可讀寫的資料庫位於 data/data/應用程式包名/databases/ 底下。
MyDBOpenHelper helper = new MyDBOpenHelper(this);
// 此時尚未建立資料庫,只是有了物件
helper.getWritableDatabase();
// 這一行才會真正建立或開啟資料庫
SQLite 有幾個和直覺不同的特性,先記起來可以少踩坑:
android_metadata 的表,用來記錄語言環境。_id,這與 Cursor 的介面約定有關。@Override
// 僅在資料庫首次建立時執行;若已存在則不會再次呼叫
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table info (_id integer primary key autoincrement,"
+ "name varchar(20), phone varchar(20))");
}
@Override
// 版本號改變時執行;oldVersion 與 newVersion 可用於跨版本升級時保留資料
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("alter table info add money varchar(10)");
}
升級策略要看產品性質:若資料必須完整保留,就寫好 ALTER TABLE 的遷移邏輯;若是壟斷性行業或資料本來就一次性的場景,也可以直接讓舊資料失效,請使用者重新輸入。
介面上放四顆按鈕,分別觸發四個方法:
<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"
tools:context="com.test.databaseoper.MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="add"
android:text="add" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="update"
android:text="update" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="delete"
android:text="delete" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="query"
android:text="query" />
</LinearLayout>
插入時同樣可以用問號佔位符傳參,避免自己拼字串:
public void add(View view) {
MyDBOpenHelper helper = new MyDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
Random random = new Random();
String sql = "insert into info(name,phone) values(?,?)";
db.execSQL(sql, new Object[]{"lisi" + random.nextInt(100), "453231"});
db.close();
}
public void query(View view) {
MyDBOpenHelper helper = new MyDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
String sql = "select * from info";
Cursor cursor = db.rawQuery(sql, null);
while (cursor.moveToNext()) {
String id = cursor.getString(0);
String name = cursor.getString(1);
String phone = cursor.getString(2);
System.out.println(id + " " + name + " " + phone);
}
cursor.close();
db.close();
}
官方提供的 ContentValues 搭配 insert/delete/update/query,語意更清楚,也不必自己處理引號與跳脫。
public void add(View view) {
MyDBOpenHelper helper = new MyDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
Random random = new Random();
ContentValues values = new ContentValues();
values.put("name", "lisi" + random.nextInt(100));
values.put("phone", "12345678");
// insert(表名, 需填補空值的列, 要插入的值)
long id = db.insert("info", null, values);
if (id != -1) {
Toast.makeText(this, "添加成功,添加在" + id + "行", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "添加失敗", Toast.LENGTH_SHORT).show();
}
db.close();
}
public void delete(View view) {
MyDBOpenHelper helper = new MyDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
// delete(表名, 條件, 條件參數);回傳刪除的列數,未刪到則為 0
int result = db.delete("info", null, null);
db.close();
if (result != 0) {
Toast.makeText(this, "刪除" + result + "行", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "刪除失敗", Toast.LENGTH_SHORT).show();
}
}
public void update(View view) {
MyDBOpenHelper helper = new MyDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
// update(表名, 值, 條件, 條件參數);回傳修改的列數
ContentValues values = new ContentValues();
values.put("name", "lisi");
values.put("phone", "12345678");
int result = db.update("info", values, null, null);
db.close();
if (result != 0) {
Toast.makeText(this, "修改了第" + result + "行", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "修改失敗", Toast.LENGTH_SHORT).show();
}
}
public void query(View view) {
MyDBOpenHelper helper = new MyDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
// query(表名, 欄位, 條件, 條件參數, groupBy, having, orderBy)
Cursor cursor = db.query("info", new String[]{"_id", "name", "phone"},
null, null, null, null, null);
while (cursor.moveToNext()) {
String id = cursor.getString(0);
String name = cursor.getString(1);
String phone = cursor.getString(2);
System.out.println(id + " " + name + " " + phone);
}
cursor.close();
db.close();
}
三種常見方式:把語句查詢的結果印到 logcat;把資料庫檔案從應用程式專用資料區 pull 出來再用工具軟體開啟;或者直接用命令列操作。

命令列下若出現中文亂碼,可以調整編碼頁:chcp 65001(65001 即 UTF-8 的代碼頁)。
Android 抽屜式側滑導航菜單 DrawerLayout 實現代碼
瀏覽了很多應用後發現,這種側滑抽屜式的菜單體驗非常好。 它不必切換到另一個頁面,也不用去按菜單的物理按鍵,只需在界面上一個操作,菜單便滑了出來,而且能容納相當多的內容。
Android 仿微信/支付寶的六位簡易密碼輸入框
做支付類 App 幾乎都會遇到簡易密碼輸入框。一開始自己的思路不太順,後來到 GitHub 上找到一個開源實作,寫得相當漂亮,先附上來源: https://github.
仿百度地圖街景效果實現:MapView 與 PanoView 的聯動
用過百度地圖的同學應該都熟悉街景功能——能看到不少地方的實景畫面。本文就以街景效果的實現為線索,走一遍完整流程。 百度在開放平台為開發者準備了豐富的 SDK 與文檔。關於
用 RecyclerView 打造類支付寶首頁:網格布局與分隔線實踐
在 Android 應用中,首頁常常會採用「上方輪播圖、下方功能入口」的結構。早期我們通常會使用 GridView 來實現下方網格,但隨著 RecyclerView 的普