編輯:關於 Android 程式設計
SQLite 是 Android 系統內嵌的數據庫,小巧強大,能勝任大多數 SQL 語句的處理工作,本質上就是一個文件。不過它並不像 PC 端的 MySQL 那樣功能齊全,而且 Android 不允許透過 JDBC 操作遠程數據庫,因此需要服務端數據時,只能走 WebService 與 PHP、Servlet 等後端交互。
SQLiteDatabase 類代表一個數據庫對象,所有操作都透過它完成。
三個靜態方法可以很方便地打開或新建數據庫:
static SQLiteDatabase openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flag);
static SQLiteDatabase openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory);
static SQLiteDatabase openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory);
execSQL(String sql, Object[] bindArgs) 與 execSQL(String sql) 用於執行非查詢語句;rawQuery(String sql, String[] selectionArgs) 用於查詢;beginTransaction() 與 endTransaction() 則用來包裹事務。
查詢結果以 Cursor 表示,作用類似 JDBC 中的 ResultSet,透過 move()、moveToFirst()、moveToLast()、moveToNext()、moveToPosition()、moveToPrevious() 等方法定位到需要的記錄行。
main.xml
<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=".Main" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="key" />
<EditText
android:id="@+id/keys"
android:layout_width="100sp"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="value" />
<EditText
android:id="@+id/values"
android:layout_width="100sp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:text="submit" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
填充列表用的 mytextview.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/listkey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left" />
<TextView
android:id="@+id/listvalue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="300sp" />
</LinearLayout>
Main.java
這裡用 try-catch 判斷表是否存在:插入失敗就說明表還沒建,於是建表後重試。雖然能跑,但更規範的做法是先用 CREATE TABLE IF NOT EXISTS 在 onCreate 中一次性建好。
package com.app.main;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Main extends Activity {
EditText ed1 = null;
EditText ed2 = null;
Button btn = null;
ListView lv = null;
SQLiteDatabase db = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed1 = (EditText) this.findViewById(R.id.keys);
ed2 = (EditText) this.findViewById(R.id.values);
btn = (Button) this.findViewById(R.id.btn);
lv = (ListView) this.findViewById(R.id.lv);
db = SQLiteDatabase.openOrCreateDatabase(
this.getFilesDir().toString() + "/my.db3", null);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String key = ed1.getText().toString();
String value = ed2.getText().toString();
try {
insertData(db, key, value);
Cursor cursor = db.rawQuery("select * from tb_info", null);
inflateListView(cursor);
} catch (Exception e) {
String sql = "create table tb_info(_id integer primary key "
+ "autoincrement,db_key varchar(20),db_value varchar(50))";
db.execSQL(sql);
insertData(db, key, value);
Cursor cursor = db.rawQuery("select * from tb_info", null);
inflateListView(cursor);
}
}
});
}
/** 向數據庫中插入數據 */
private void insertData(SQLiteDatabase db, String key, String value) {
db.execSQL("insert into tb_info values (null,?,?)",
new String[]{key, value});
}
/** 向 ListView 中填充數據 */
@SuppressLint("NewApi")
public void inflateListView(Cursor cursor) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(Main.this,
R.layout.mytextview, cursor,
new String[]{"db_key", "db_value"},
new int[]{R.id.listkey, R.id.listvalue},
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
lv.setAdapter(adapter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (db != null && db.isOpen()) {
db.close();
}
}
}
效果如下:

這裡有一個容易踩的坑需要特別指出:用 SimpleCursorAdapter 封裝 Cursor 時,要求底層表的主鍵列名必須是 _id,因為 SimpleCursorAdapter 只認這個列名。範例中把 _id integer primary key autoincrement 寫進建表語句,正是為了這個原因。
EventBus 實戰:用發布訂閱模式取代 Intent 與 Handler 傳遞訊息
做過 Android 開發,遲早都會碰到 EventBus。這是一個針對 Android 最佳化的發布/訂閱事件總線,主要用來取代 Intent、Handler、Broa
自訂 View 更新疑難:為什麼 draw() 拿不到改過的成員變數
做音樂播放器的時候遇到一個很怪的現象,記錄一下整個排查過程,因為這個坑很值得講。 問題描述 我在自訂的歌詞 View 裡有一個成員變數 lrcIndex,draw 裡會
手機進水最佳處理方法
手機進水後的正確處理方法 手機進水後,處理方式會直接影響能否恢復。首先要避免甩動手機,以免水分在內部擴散。 自然晾干 可將手機按落水姿態垂直或水平放置,等待自然晾干。此
Activity 生命週期全解析:從 AMS 到主線程的消息流轉
寫 Android 一段時間之後,你一定會發現 Activity 的生命週期不只是「幾個 callback 依序被呼叫」這麼簡單。它背後牽涉到系統行程與應用行程的跨行程溝