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

SQLite 增刪改查完整實作:以通訊錄為例

編輯:關於 Android 開發

本文以一個「通訊錄」小專案為例,完整示範 Android 中 SQLite 的增刪改查操作,涵蓋 DAO 層、實體類、資料庫幫助類、Activity 邏輯與布局檔案。

PersonDao1.java(資料訪問層)

package mm.shandong.com.testsqlsqllite.dao;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import mm.shandong.com.testsqlsqllite.entity.Person;
import mm.shandong.com.testsqlsqllite.util.StudySQLiteOpenHelper;

public class PersonDao1 {
    Context context;
    StudySQLiteOpenHelper studySQLiteOpenHelper;
    public PersonDao1(Context context) {
        this.context = context;
        studySQLiteOpenHelper = new StudySQLiteOpenHelper(context, "androidStudy.db", 7);
    }
    public void addPerson(Person person) {
        SQLiteDatabase db = studySQLiteOpenHelper.getWritableDatabase();
        String sql = "insert into person(_id,name,sex,age,code) values(null,?,?,?,?)";
        db.execSQL(sql,new Object[]{person.getName(), person.getSex(), person.getAge(), person.getCode()});
    }
    public void deletePerson(Person person) {
        SQLiteDatabase db = studySQLiteOpenHelper.getWritableDatabase();
        String sql = "delete from person where _id=?";
        db.execSQL(sql, new Object[]{person.get_id()});
    }
    public void updatePerson(Person person) {
        SQLiteDatabase db = studySQLiteOpenHelper.getWritableDatabase();
        String sql = "update person set name=?,sex=?,age=?,code=? where _id=?";
        db.execSQL(sql, new Object[]{person.getName(), person.getSex(), person.getAge(), person.getCode(), person.get_id()});
    }
    public List<Person> getAllPerson() {
        List<Person> persons = new ArrayList<Person>();
        SQLiteDatabase db = studySQLiteOpenHelper.getWritableDatabase();
        String sql = "select * from person";
        Cursor cursor = db.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String sex = cursor.getString(cursor.getColumnIndex("sex"));
            int age = cursor.getInt(cursor.getColumnIndex("age"));
            String code = cursor.getString(cursor.getColumnIndex("code"));
            int _id = cursor.getInt(cursor.getColumnIndex("_id"));
            Person person = new Person(name, sex, age, code);
            person.set_id(_id);
            persons.add(person);
        }
        return persons;
    }
}

Person 實體類

package mm.shandong.com.testsqlsqllite.entity;
import java.io.Serializable;

public class Person implements Serializable{
    private String name;
    private int age;
    private String code;
    private String sex;
    private String first_letter;
    private int _id;
    public String getSex() { return sex; }
    public void setSex(String sex) { this.sex = sex; }
    public void set_id(int _id) { this._id = _id; }
    public int get_id() { return _id; }
    public void setFirst_letter(String first_letter) { this.first_letter = first_letter; }
    public String getFirst_letter() { return first_letter; }
    public Person(){ }
    public Person(String name, int age, String code){ this.name=name; this.age=age; this.code=code; }
    public Person(String name,String sex, int age, String code){ this.name=name; this.age=age; this.code=code; this.sex=sex; }
    @Override public String toString() { return name +" "+age+" "+code; }
    public void setAge(int age) { this.age = age; }
    public void setCode(String code) { this.code = code; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public String getCode() { return code; }
    public String getName() { return name; }
}

StudySQLiteOpenHelper(資料庫幫助類)

package mm.shandong.com.testsqlsqllite.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class StudySQLiteOpenHelper extends SQLiteOpenHelper {
    String dataBase_name;
    Context context;
    String create_TABLE_sql="create table person(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
        "name varchar(30),age integer,sex varchar(30),code varchar(30))";
    String delete_Sql="delete from person";
    public StudySQLiteOpenHelper(Context context, String name, int verson){
        super(context,name,null,verson);
        this.context=context;
    }
    @Override public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(create_TABLE_sql);
    }
    @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { }
}

Activity 邏輯

Activity 中透過 ListView 展示資料,並以 BaseAdapter 綁定資料;新增、刪除、修改皆透過 AlertDialog 彈窗完成,並在操作後重新載入資料、刷新列表。核心方法包括 addPerson、deletePerson、updatePerson,搭配单选按鈕標記當前選中項。完整程式碼如下:

public class TestSQLSqlLiteActivity extends AppCompatActivity {
    ListView listView;
    List<Person> persons;
    PersonDao1 personDao;
    BaseAdapter personAdapter;
    Map<String,Boolean> radioStates;
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_sqlsql_lite);
        radioStates=new HashMap<String,Boolean>();
        personDao=new PersonDao1(this);
        listView= (ListView) findViewById(R.id.listView);
        persons=personDao.getAllPerson();
        initListView();
    }
    public void initListView(){
        personAdapter=new BaseAdapter() {
            @Override public int getCount() { return persons.size(); }
            @Override public Object getItem(int position) { return persons.get(position); }
            @Override public long getItemId(int position) { return position; }
            @Override public View getView(final int position, View view, ViewGroup viewGroup) {
                view=getLayoutInflater().inflate(R.layout.item_sqlite_listview,null);
                final Person person= (Person) getItem(position);
                // ... 綁定 name/age/sex/code 與單選狀態
                return view;
            }
        };
        listView.setAdapter(personAdapter);
    }
    public void addPerson(View view){ /* 彈窗新增並寫入資料庫 */ }
    public void deletePerson(View view){ /* 依選中項刪除 */ }
    public void updatePerson(View view){ /* 彈窗修改並更新資料庫 */ }
}

布局檔案

<?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="match_parent"
    android:orientation="vertical">
    <LinearLayout android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="addPerson" android:text="新增" />
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="deletePerson" android:text="刪除" />
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="updatePerson" android:text="修改" />
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content">
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_horizontal" android:text="姓名" />
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_horizontal" android:text="編號" />
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_horizontal" android:text="年齡" />
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_horizontal" android:text="性別" />
        <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_horizontal" android:text="請選擇" />
    </LinearLayout>
    <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" />
</LinearLayout>

如需完整源碼,可留下您的電子郵件。

以上範例皆來自「安卓無憂」應用,可前往應用寶或豌豆莢下載觀看更多源碼範例。

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