編輯:關於 Android 開發
這個案例把 SQLite 的增刪改查和 ListView 結合起來:頁面上有四顆按鈕分別做新增、刪除、修改、查詢,查詢結果用 ListView 呈現。學會新聞列表那題之後,這個基本上就是延伸應用。
布局:四顆操作按鈕加一個 ListView。
<?xml version="1.0"?>
<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=".MainActivity">
<Button android:id="@+id/bt_add" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/add" />
<Button android:id="@+id/bt_del" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/del" />
<Button android:id="@+id/bt_update" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/update" />
<Button android:id="@+id/bt_query" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/query" />
<ListView android:id="@+id/lv_databases" android:layout_width="fill_parent"
android:layout_height="match_parent" />
</LinearLayout>
資料庫幫助類 MySqliteOpenHelper,onCreate 在首次建立時負責建表,onUpgrade 則在版本號改變時用來改表結構:
package com.itheima.crud;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MySqliteOpenHelper extends SQLiteOpenHelper {
public MySqliteOpenHelper(Context context) {
// context: 上下文 name: 資料庫檔案名稱 factory: 建立 cursor 用,預設 null
// version: 版本號,從 1 開始,改變時 onUpgrade 會被呼叫
super(context, "info.db", null, 1);
}
// 資料庫第一次建立時呼叫,適合做表結構初始化
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table info (_id integer primary key autoincrement, name varchar(20), phone varchar(11))");
}
// 版本號改變時才執行,適合做表結構修改
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// db.execSQL("alter table info add phone varchar(11)");
}
}
資料模型 InfoBean:
package com.itheima.crud.bean;
public class InfoBean {
public String id;
public String name;
public String phone;
}
DAO 層封裝增刪改查。這裡用的是 insert / delete / update / query 這組 API,比起手寫 SQL 更直覺,而且 update、delete、query 都會回傳受影響的行數,方便判斷是否成功:
package com.itheima.crud.dao;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.itheima.crud.MySqliteOpenHelper;
import com.itheima.crud.bean.InfoBean;
public class InfoDao {
private MySqliteOpenHelper mySqliteOpenHelper;
public InfoDao(Context context) {
mySqliteOpenHelper = new MySqliteOpenHelper(context);
}
public boolean add(InfoBean bean) {
SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
ContentValues values = new ContentValues();
values.put("name", bean.name);
values.put("phone", bean.phone);
// 回傳新行的 id,-1 代表新增失敗
long result = db.insert("info", null, values);
db.close();
return result != -1;
}
public int del(String name) {
SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
// 回傳成功刪除的行數
int result = db.delete("info", "name = ?", new String[]{name});
db.close();
return result;
}
public int update(InfoBean bean) {
SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
ContentValues values = new ContentValues();
values.put("phone", bean.phone);
int result = db.update("info", values, "name = ?", new String[]{bean.name});
db.close();
return result;
}
public ArrayList<InfoBean> query(String name) {
ArrayList<InfoBean> list = new ArrayList<InfoBean>();
SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
Cursor cursor = db.query("info", new String[]{"_id", "name", "phone"},
"name = ?", new String[]{name}, null, null, "_id asc");
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
InfoBean bean = new InfoBean();
bean.id = cursor.getInt(0) + "";
bean.name = cursor.getString(1);
bean.phone = cursor.getString(2);
list.add(bean);
}
cursor.close();
}
db.close();
return list;
}
}
QueryAdapter 把查詢結果綁到 ListView,同樣復用 convertView:
package com.itheima.crud.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.itheima.crud.bean.InfoBean;
import com.itheima.crud2_listview.R;
public class QueryAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<InfoBean> arrayList;
public QueryAdapter(Context mContext, ArrayList<InfoBean> arrayList) {
this.mContext = mContext;
this.arrayList = arrayList;
}
@Override
public int getCount() { return arrayList.size(); }
@Override
public Object getItem(int position) { return arrayList.get(position); }
@Override
public long getItemId(int position) { return position; }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView != null) {
view = convertView;
} else {
view = View.inflate(mContext, R.layout.item_database_layout, null);
}
TextView item_tv_id = (TextView) view.findViewById(R.id.item_tv_id);
TextView item_tv_name = (TextView) view.findViewById(R.id.item_tv_name);
TextView item_tv_phone = (TextView) view.findViewById(R.id.item_tv_phone);
InfoBean infoBean = arrayList.get(position);
item_tv_id.setText(infoBean.id);
item_tv_name.setText(infoBean.name);
item_tv_phone.setText(infoBean.phone);
return view;
}
}
MainActivity 則負責在 OnCreate 中初始化資料庫(呼叫 getReadableDatabase 觸發建表),並在四顆按鈕的點擊事件裡呼叫對應的 DAO 方法,查詢時再把結果包裝成 QueryAdapter 設給 ListView。
小結:整個架構分層清楚——Activity 負責交互、DAO 負責資料存取、Adapter 負責資料綁定、Bean 負責資料承載。把這個分層模式吃透,之後不管是新聞列表還是資料庫列表,都是同一套套路。
Android Accessibility 輔助功能深入實戰:一念天堂,一念地獄
Android Accessibility 輔助功能深入實戰:一念天堂,一念地獄 0x00 什麼是 Accessibility(輔助功能) 考量到部分使用者因視力、身體或
Android 自訂 Dialog 三步驟:打造居中顯示圖片的彈出視窗
Android 自訂 Dialog 三步驟:打造居中顯示圖片的彈出視窗 做 Android 應用時,自訂 Dialog 幾乎是必備技能,因為系統預設的 Dialog 樣式
Android 自定義倒數計時 TextView:列表項中的剩餘時間顯示
Android 自定義倒數計時 TextView:列表項中的剩餘時間顯示 在音樂或音頻列表頁面中,常需要在播放時顯示剩餘時間,暫停時則停止倒數。若使用 ListView,
釋放 Android 的函數式能量(一):Kotlin Lambda 表達式入門
背景:為何要在 Android 上談函數式 Java 8 已內建若干函數式工具,但 Android 開發者過去很長一段時間無法立即使用。既然官方語言支援落後,社群便轉而尋