編輯:Android 開發實例
Android 內建 SQLite,是所有本機資料儲存方案裡最正規的一種。以下以「學生資料表」為例,走一遍建立、新增、查詢、刪除的完整流程。
第一步永遠是繼承 SQLiteOpenHelper,把建表邏輯與版本管理交給它:
package com.SQLiteTest2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MyOpenHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "student";
public static final String TABLE_NAME = "student_information";
public static final String ID = "_id";
public static final String NUMBER = "number";
public static final String NAME = "name";
public MyOpenHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists " + TABLE_NAME + " ("
+ ID + " integer primary key,"
+ NUMBER + " varchar,"
+ NAME + " varchar)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
幾個設計慣例值得說明:_id 這個欄位名稱不是隨便取的,Android 的 CursorAdapter 等元件預設會去找名為 _id 的欄位作為主鍵,自訂其他名稱會導致「no such column _id」錯誤。onCreate() 只在資料庫首次建立時被呼叫一次,之後不會再觸發。而 onUpgrade() 則在你把 version 號碼往上調時被呼叫,正式專案中應在這裡寫入 DROP TABLE 加 CREATE TABLE 的遷移邏輯,否則舊資料會殘留並造成衝突。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/enter"
/>
<LinearLayout
android:orientation="horizontal"
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/number"
/>
<EditText
android:id="@+id/number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></EditText>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:id="@+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name"
/>
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></EditText>
</LinearLayout>
<Button
android:id="@+id/submit"
android:text="@string/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<TextView
android:id="@+id/IdLongitude"
android:textSize="16px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/IdLatitude"
android:textSize="16px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
import static com.SQLiteTest2.MyOpenHelper.*;
public class SQLiteTest2 extends Activity {
MyOpenHelper myHelper;
EditText [] textArray;
Button btn_save;
int [] textIds = {
R.id.number,
R.id.name
};
View.OnClickListener myListener = new View.OnClickListener() {
@Override
public void onClick(View v) { // 保存按鈕按下觸發該事件
String [] strArray = new String[textArray.length];
for(int i = 0; i < strArray.length; i++){
// 獲得用戶輸入的信息數組
strArray[i] = textArray[i].getText().toString().trim();
}
insert(strArray);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textArray = new EditText[textIds.length];
for(int i=0;i<textIds.length;i++){
textArray[i] = (EditText)findViewById(textIds[i]);
}
myHelper = new MyOpenHelper(this, MyOpenHelper.DB_NAME, null, 1);
btn_save = (Button) findViewById(R.id.submit);
btn_save.setOnClickListener(myListener);
}
public void insert(String [] strArray) {
SQLiteDatabase db = myHelper.getWritableDatabase(); // 獲得數據庫對象
ContentValues values = new ContentValues();
values.put(NUMBER, strArray[0]);
values.put(NAME, strArray[1]);
long count = db.insert(TABLE_NAME, ID, values); // 插入數據
db.close();
if(count == -1){
Toast.makeText(this, "插入失敗!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "插入成功!", Toast.LENGTH_SHORT).show();
}
}
}
新增資料時,用 ContentValues 以 key-value 形式裝填欄位值,再交給 db.insert()。這比字串拼接 SQL 安全得多,也不必處理引號與特殊字元。回傳值為 -1 代表失敗,其餘為新資料列的 row id。
public void deleteContact(int id) {
SQLiteDatabase db = myHelper.getWritableDatabase(); // 獲得數據庫對象
db.delete(TABLE_NAME, ID + "=?", new String[]{id + ""});
db.close();
}
刪除時務必使用 "?=?" 佔位符搭配參數陣列的寫法,而非字串拼接。這能有效防止 SQL Injection——即使是內部資料,養成習慣也總是好事。
由於原文聚焦於增與刪,這裡補上另外兩個操作的標準寫法:
// 查詢:回傳 Cursor,記得遍历後關閉
SQLiteDatabase db = myHelper.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String number = cursor.getString(cursor.getColumnIndex(NUMBER));
String name = cursor.getString(cursor.getColumnIndex(NAME));
cursor.moveToNext();
}
cursor.close();
}
// 修改:以 ContentValues 帶入新值,第三個參數為條件
public void updateContact(int id, String newName) {
SQLiteDatabase db = myHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME, newName);
db.update(TABLE_NAME, values, ID + "=?", new String[]{id + ""});
db.close();
}
Android 應用本地化:讓 App 說出使用者的語言
同一個 App,可能同時被東京、米蘭、聖保羅的使用者打開。要讓它在不同地區都顯得自然,就不能把文字寫死在程式碼裡,而必須處理語言、數字格式、日期等在地性差異。本章說明 A
Android JSON 資料解析:JSONObject 與天氣資訊抓取
在 Android 開發中,JSON 解析幾乎是網路應用的必備技能。無論是氣象、新聞、社群或商品資料,後端常會以 JSON 格式回傳結果。本文說明如何從 JSON 中取出
打造可橫向又縱向滾動的表格:ListView 固定列頭實作
由於專案需求,我們需要一個既能橫向滾動、又能縱向滾動,還得應付大資料量(多列)的表格視圖。折騰幾天終於搞定,做個示範,先貼圖: 來看看背後的思路: 設計思路 1. 上
Android 單元測試實例分析:從設定到執行
本文以實例說明 Android 單元測試的用法。在實際開發中,撰寫 Android 軟體的過程需要不斷測試,而 JUnit 測試框架正是正規開發必備的技術。透過 JUni