Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ListView 顯示資料庫數據:SQLite 增刪改查整合實作

編輯:關於 Android 開發

Android ListView 顯示資料庫數據:SQLite 增刪改查整合實作


這個案例把 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 負責資料承載。把這個分層模式吃透,之後不管是新聞列表還是資料庫列表,都是同一套套路。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved