達內課程-SQLite(下)


最后一節,來做一個關於SQLite的項目
先做出以下界面

第一個頁面MainActivity對應的布局activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.xx.sqliteproject.MainActivity" android:orientation="vertical">

    <Button  android:id="@+id/btn_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="添加聯系人"/>

    <ListView  android:id="@+id/lv_contacts" android:layout_width="match_parent" android:layout_height="match_parent"/>

</LinearLayout>

第二個ContactFormActivity對應的布局activity_contact_form

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.xx.sqliteproject.ContactFormActivity" android:orientation="vertical">

    <TextView  android:layout_width="match_parent" android:layout_height="wrap_content" android:text="請輸入聯系人信息"/>

    <EditText  android:id="@+id/et_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" android:hint="請輸入聯系人姓名"/>
    <EditText  android:id="@+id/et_age" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:hint="請輸入聯系人年齡"/>
    <EditText  android:id="@+id/et_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:hint="請輸入聯系人電話"/>
    <EditText  android:id="@+id/et_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:hint="請輸入聯系人Email"/>

    <Button  android:id="@+id/btn_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="保存"/>

</LinearLayout>

我們可以用一個DBOpenHelper來幫助我們管理數據庫,以免反復執行出錯

public class DBOpenHelper extends SQLiteOpenHelper{

    //修改原來的構造方法
   /* public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); }*/
    public DBOpenHelper(Context context) {
        super(context, "test.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //當創建數據庫時,直接創建數據表
        String sql = "CREATE TABLE users ("+
                "_id INTEGER PRIMARY KEY AUTOINCREMENT, "+
                "_name VARCHAR(10) UNIQUE NOT NULL, "+
                "_age INTEGER, "+
                "_phone CHAR(11), "+
                "_email VARCHAR(31) UNIQUE"+
                ")";
        sqLiteDatabase.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        //當升級時
    }
}

DBOpenHelper的onCreate()方法確保創建數據庫的時候執行,不創建的時候不反復執行

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_add;
    private ListView lv_contacts;

    SQLiteOpenHelper s;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        DBOpenHelper dbOpenHelper = new DBOpenHelper(this);
        //必須調用以下其中一個方法才能執行創建數據庫
        //dbOpenHelper.getReadableDatabase();
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    }

    private void initView() {
        btn_add = findViewById(R.id.btn_add);
        lv_contacts = findViewById(R.id.lv_contacts);

        btn_add.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Intent  intent = new Intent(this,ContactFormActivity.class);
        startActivity(intent);
    }
}

項目結構如下圖
這里寫圖片描述

創建一個Person類

public class Person {
    private String name;
    private int age;
    private String phone;
    private String email;

    public Person() {
    }

    public Person(String name, int age, String phone, String email) {
        this.name = name;
        this.age = age;
        this.phone = phone;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

創建接口IDao,實現相關功能

public interface IDao<T> {
    long insert(T t);
}

創建PersonDao

public class PersonDao implements IDao<Person> {
    private Context context;

    public PersonDao(Context context) {
        setContext(context);
    }

    private void setContext(Context context) {
        if(context == null){
            throw new IllegalArgumentException("參數context不能為空");
        }
        this.context = context;
    }

    @Override
    public long insert(Person person) {
        //獲取SQLiteDatabase對象
        DBOpenHelper dbOpenHelper = new DBOpenHelper(context);
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        //執行業務,增加數據
        String table = "users";
        String nullColumnHack = "_id";
        ContentValues values = new ContentValues();
        values.put("_name",person.getName());
        values.put("_age",person.getAge());
        values.put("_phone",person.getPhone());
        values.put("_email",person.getEmail());
        long id = db.insert(table,nullColumnHack,values);

        //釋放資源
        db.close();
        db = null;

        //返回
        return id;
    }
}

ContractFormActivity

public class ContactFormActivity extends AppCompatActivity implements View.OnClickListener{
    private EditText etUsername;
    private EditText etAge;
    private EditText etPhone;
    private EditText etEmail;
    private Button btnSave;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_form);

        initViews();
        setListeners();
    }

    private void setListeners() {
        btnSave.setOnClickListener(this);
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etAge = findViewById(R.id.et_age);
        etPhone = findViewById(R.id.et_phone);
        etEmail = findViewById(R.id.et_email);
        btnSave = findViewById(R.id.btn_save);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_save:
                //獲取表單中的數據
                String name = etUsername.getText().toString().trim();
                String phone = etPhone.getText().toString().trim();
                String email = etEmail.getText().toString().trim();
                int age = Integer.parseInt(etAge.getText().toString());

                Person person = new Person(name,age,phone,email);
                PersonDao personDao = new PersonDao(this);
                long id = personDao.insert(person);
                if(id == -1){
                    Toast.makeText(this,"姓名或電子郵件可能沖突!",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this,"數據增加成功",Toast.LENGTH_SHORT).show();
                    etUsername.setText(null);
                    etPhone.setText(null);
                    etEmail.setText(null);
                    etAge.setText(null);
                }
                break;
        }
    }
}

運行程序

可以在添加聯系人的列表增加返回按鈕

添加點擊監聽,點擊時,finish()當前頁面返回上一頁面

在上一頁中顯示聯系人列表

IDao中增加查詢方法

public interface IDao<T> {
    long insert(T t);

    List<T> query(String whereClause,String whereArgs,String orderBy);
}

PersonDao中完善query方法

 @Override
    public List<Person> query(String whereClause, String[] whereArgs, String orderBy) {
        //聲明返回值
        List<Person> persons = new ArrayList<Person>();
        //獲取SQLiteDatabase對象
        DBOpenHelper dbOpenHelper = new DBOpenHelper(context);
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        //執行業務:查詢數據
        String table = "users";
        String[] columns = {"_id","_name","_age","_phone","_email"};
        Cursor c = db.query(table, columns, whereClause, whereArgs, null, null, orderBy);
        //將數據封裝到返回值中
        for(c.moveToFirst();!c.moveToLast();c.moveToNext()){
            Person p = new Person();
            p.setId(c.getInt(0));
            p.setName(c.getString(1));
            p.setAge(c.getInt(2));
            p.setPhone(c.getString(3));
            p.setEmail(c.getString(4));
            persons.add(p);
        }

        //釋放資源
        db.close();
        db = null;
        //返回
        return persons;
    }

因為查詢字段中有id字段,所以Person類中增加id字段

public class Person {
    private int id;
    private String name;
    private int age;
    private String phone;
    private String email;

    public Person() {
    }

    public Person(String name, int age, String phone, String email) {
        this.name = name;
        this.age = age;
        this.phone = phone;
        this.email = email;
    }

    public Person(int id, String name, int age, String phone, String email) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.phone = phone;
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    ......
}

MainActivity中准備顯示列表的Adaper,把之前寫好的BaseAdapter拿過來用
BaseAdapter的源碼在達內課程-音樂播放器3.0(上)

新建PersonAdapter

這里寫代碼片

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com