【Android】_SQLiteDemo_学生管理系统

版权声明:本文为博主原创文章,转载请注明出处!如有问题,欢迎指正。 https://blog.csdn.net/cungudafa/article/details/84726168

(一)基于SQLite的Android应用

1. 关于SQLite
SQLite 是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是在世界上最广泛部署的 SQL 数据库引擎。SQLite 源代码不受版权限制。
SQLite的核心引擎本身不依赖第三方的软件,在我们开发时直接使用即可。

2. SQLiteDatabase、SQLiteOpenHelper、Cursor(游标) 使用解释

  • SQLiteDatabase:
    SQLiteDatabase是SQLite数据库类, 用于创建数据库.

  • SQLiteOpenHelper:
    SQLiteOpenHelper这个类用来管理数据库。包括创建 和更新 数据库。所以我们只要继承SQLiteOpenHelper类来就可以对数据库进行管理。

  • Cursor(游标):
    SQLite查询的结果是返回一个游标(Cursor)。类似于我们在java学习数据库操作中的ResultSet类差不多, rawQuery(String sql, String[] selectionArgs)。通过移动游标来进行数据的查询。

(二)创建SQLiteDemo教程

目标:通过一个SQLite的数据库的操作实现学生信息的增删改查
1)实现多个学生信息的添加和显示
2)用EditText实现姓名、年龄的输入,并有输入校验(空校验,数字校验)
3)用AutoCompleteTextView的实现专业的输入,并有提示功能。
4)通过CheckBox实现多门课程选择
5)通过Radio实现性别
6)用下拉框选择学院
7)用日期控件实现入学时间的输入
8)点击提交按钮后,将输入的信息,用列表控件ListView显示在另一个Activity。
9)实现列表中学生信息的编辑和删除。

1. 效果实现图

增添:
在这里插入图片描述
查询:
在这里插入图片描述
删除和修改:
在这里插入图片描述

2. 项目结构图

2.1 项目分配:

在这里插入图片描述

扫描二维码关注公众号,回复: 4342312 查看本文章

menu.xml不是放在layout目录下,而是放在menu目录下。

  • 在res下->右键新建Resource Directory->设置type为menu->命名为menu
    在这里插入图片描述
  • 在menu文件夹下->新建Resource File->命名为menu
    在这里插入图片描述

2.2 自定义类的Java文件:

StudentDao、StudentDBHelper、Student、TableContanst
  • 在MainActivity.java文件目录下右键新建StudentDao.class类:
    在这里插入图片描述
  • 重复上述步骤新建StudentDBHelper、Student、TableContanst类。

2.3美化样式文件:
在这里插入图片描述

2.4 其他文件:

string .xml、color.xml、styles.xml、AndroidManifest.xml(自定义的活动需要手动添加到此文件中)

2.5 完成目录:
在这里插入图片描述

3. 具体的编码实现

3.1xml布局

在这里插入图片描述

  1. 布局界面引入了ListView,activity_main.xml:
    在这里插入图片描述

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <RelativeLayout android:id="@+id/RelativeLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#a1afc9">
        <Button
            android:id="@+id/bn_search_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="                  搜      索                  "
            android:textSize="15sp"
            android:textColor="#a1afc9"
            android:background="@drawable/shape_button_white"
            android:gravity="center"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="2dp"/>
        <Button
            android:gravity="center"
            android:text=" 添 加 "
            android:id="@+id/btn_add_student"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/bn_search_id"
            android:layout_toLeftOf="@+id/bn_select"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="2dp"
            android:textColor="#ffffff"
            android:textSize="15sp"
            android:background="@drawable/shape_button"/>
        <Button
            android:gravity="center"
            android:text="选 择"
            android:id="@+id/bn_select"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="2dp"
            android:textColor="#ffffff"
            android:textSize="15sp"
            android:background="@drawable/shape_button"></Button>
    </RelativeLayout>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="                   ID          姓 名          年 龄            性 别  "
        android:textSize="18sp"
        android:textColor="#4b5cc4"
        />
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <LinearLayout
        android:orientation="horizontal"
        android:id="@+id/showLiner"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">
        <Button
            android:id="@+id/bn_delete"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="删除"
            android:enabled="false"
            />
        <Button
            android:id="@+id/bn_selectall"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="全选"
            />
        <Button
            android:id="@+id/bn_canel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="取消"
            />
    </LinearLayout>
</LinearLayout>
  1. 自定义student_list_item.xml用于存放学生列表
    在这里插入图片描述

student_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="130px"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:background="@drawable/icon_man" />
    <TextView
        android:id="@+id/tv_stu_id"
        android:layout_width="fill_parent"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:id="@+id/tv_stu_name"
        android:layout_width="fill_parent"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <TextView android:id="@+id/tv_stu_age"
        android:layout_width="fill_parent"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:id="@+id/tv_stu_sex"
        android:layout_width="fill_parent"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <TextView
        android:id="@+id/tv_stu_likes"
        android:layout_width="fill_parent"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:visibility="gone"/>
    <TextView android:id="@+id/tv_stu_phone"
        android:layout_width="fill_parent"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:visibility="gone"/>
    <TextView android:id="@+id/tv_stu_traindate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:visibility="gone"/>
    <TextView
        android:id="@+id/tv_stu_modifyDateTime"
        android:layout_width="fill_parent"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:visibility="gone"/>

    <CheckBox
        android:id="@+id/cb_box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:visibility="gone"
        android:checked="false"
        android:focusable="false"/>
</LinearLayout>
  1. 自定义menu.xml,用于对学生信息进行操作:
    在这里插入图片描述

menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="40dip"
    android:layout_width="80dip">
    <group android:checkableBehavior="single">
        <item android:id="@+id/delete" android:title="删除学员信息" />
        <item android:id="@+id/look" android:title="详细信息" />
        <item android:id="@+id/write" android:title="修改学员信息" />
    </group>
</menu>
  1. 创建activity,命名为activity_student_info.xml,用于单条学生信息查看,相应.java文件见后文;
    在这里插入图片描述

activity_student_info.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#a1afc9"
    android:padding="5dip"  >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:gravity="center"
        android:text="学生信息"
        android:textColor="#4b5cc4"
        android:textSize="30dp"/>
    <TextView android:id="@+id/id2_text_id"
        android:layout_width="80dip"
        android:layout_height="40dip"
        android:layout_marginRight="5dip"
        android:layout_marginTop="50dip"
        android:layout_marginBottom="5dip"
        android:textSize="16sp"
        android:gravity="left|center_vertical"
        android:text="学员ID:"  />
    <TextView android:id="@+id/tv_info_id"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:layout_toRightOf="@id/id2_text_id"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/id2_text_id"
        android:gravity="left|center_vertical"/>
    <TextView android:id="@+id/name2_text_id"
        android:layout_width="80dip"
        android:layout_height="40dip"
        android:layout_marginRight="5dip"
        android:layout_marginTop="8dip"
        android:layout_marginBottom="8dip"
        android:layout_below="@id/id2_text_id"
        android:layout_alignLeft="@id/id2_text_id"
        android:textSize="16sp"
        android:gravity="left|center_vertical"
        android:text="姓名:"  />
    <TextView android:id="@+id/tv_info_name"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:layout_toRightOf="@id/name2_text_id"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/name2_text_id"
        android:gravity="left|center_vertical"  />
    <TextView android:id="@+id/age2_text_id"
        android:layout_width="80dip"
        android:layout_height="40dip"
        android:gravity="left|center_vertical"
        android:layout_marginRight="5dip"
        android:layout_below="@id/name2_text_id"
        android:layout_marginBottom="8dip"
        android:textSize="16sp"
        android:text="年龄:"  />
    <TextView android:id="@+id/tv_info_age"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:layout_toRightOf="@id/age2_text_id"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/age2_text_id"
        android:gravity="left|center_vertical"  />
    <TextView android:id="@+id/sex2_text_id"
        android:layout_width="80dip"
        android:layout_height="40dip"
        android:gravity="left|center_vertical"
        android:layout_below="@id/age2_text_id"
        android:layout_alignLeft="@id/age2_text_id"
        android:layout_marginRight="5dip"
        android:layout_marginBottom="8dip"
        android:text="性别:"
        android:textSize="16sp"  />
    <TextView
        android:id="@+id/tv_info_sex"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:layout_toRightOf="@id/sex2_text_id"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/sex2_text_id"
        android:gravity="left|center_vertical"   />
    <TextView android:id="@+id/like2_text_id"
        android:layout_width="80dip"
        android:layout_height="40dip"
        android:gravity="left|center_vertical"
        android:layout_below="@id/sex2_text_id"
        android:layout_alignLeft="@id/sex2_text_id"
        android:layout_marginRight="5dip"
        android:layout_marginBottom="8dip"
        android:text="专业:"
        android:textSize="16sp"  />
    <TextView android:layout_height="40dip"
        android:id="@+id/tv_info_likes"
        android:layout_width="wrap_content"
        android:layout_toRightOf="@id/like2_text_id"
        android:layout_below="@id/sex2_text_id"
        android:layout_marginRight="52dip"
        android:gravity="left|center_vertical"/>
    <TextView android:id="@+id/contact2_text_id"
        android:layout_width="80dip"
        android:layout_height="40dip"
        android:gravity="center_vertical|left"
        android:layout_marginRight="5dip"
        android:layout_below="@id/like2_text_id"
        android:layout_marginBottom="5dip"
        android:textSize="16sp"
        android:text="联系电话:"  />
    <TextView android:id="@+id/tv_info_phone"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:layout_toRightOf="@id/contact2_text_id"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/contact2_text_id"
        android:gravity="center_vertical|left"  />
    <TextView android:id="@+id/train2_time_text_id"
        android:layout_width="80dip"
        android:layout_height="40dip"
        android:gravity="center_vertical|left"
        android:layout_marginRight="5dip"
        android:layout_below="@id/contact2_text_id"
        android:layout_marginBottom="8dip"
        android:textSize="16sp"
        android:text="入学日期:"  />
    <TextView android:id="@+id/tv_info_train_date"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:layout_toRightOf="@id/train2_time_text_id"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/train2_time_text_id"
        android:gravity="center_vertical|left"  />
    <Button android:id="@+id/back_to_list_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="Go back"
        android:textSize="20sp"
        android:layout_below="@id/train2_time_text_id"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:onClick="goBack"
        android:background="@drawable/shape_button_white"
        android:textColor="#a1afc9">
    </Button>
</RelativeLayout>
  1. 创建activity,命名为activity_add_student.xml,用于添加学生信息,相应.java文件见后文;在这里插入图片描述

activity_add_student.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"
    android:scrollbarStyle="outsideInset" >
    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:padding="5dip"  >
        <TextView
            android:id="@+id/tv1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="student info"
            android:textSize="25sp"
            android:textColor="#4b5cc4"/>

        <TextView android:id="@+id/tv_stu_text_id"
            android:layout_width="80dip"
            android:layout_height="40dip"
            android:gravity="center_vertical|right"
            android:layout_marginRight="5dip"
            android:layout_below="@id/tv1"
            android:layout_marginTop="20dip"
            android:layout_marginBottom="5dip"
            android:textSize="16sp"
            android:text="学员ID:"  />
        <TextView android:id="@+id/tv_stu_id"
            android:layout_width="fill_parent"
            android:layout_height="40dip"
            android:text="未分配ID"
            android:layout_toRightOf="@id/tv_stu_text_id"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@id/tv_stu_text_id"
            android:gravity="center"
            android:background="#ffffff"
            android:textColor="#000000"
            android:textSize="16sp"  />
        <TextView android:id="@+id/tv_name_text"
            android:layout_width="80dip"
            android:layout_height="40dip"
            android:gravity="center_vertical|right"
            android:layout_marginRight="5dip"
            android:layout_below="@id/tv_stu_text_id"
            android:layout_alignLeft="@id/tv_stu_text_id"
            android:layout_marginBottom="5dip"
            android:textSize="16sp"
            android:text="姓名:"  />
        <EditText android:id="@+id/et_name"
            android:layout_width="fill_parent"
            android:layout_height="40dip"
            android:layout_toRightOf="@id/tv_name_text"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@id/tv_name_text"
            android:hint="请输入姓名"
            android:inputType="textPersonName"
            android:paddingLeft="20dip"
            android:background="@drawable/shape_edit"/>
        <TextView android:id="@+id/tv_age_text"
            android:layout_width="80dip"
            android:layout_height="40dip"
            android:gravity="center_vertical|right"
            android:layout_marginRight="5dip"
            android:layout_below="@id/tv_name_text"
            android:layout_marginBottom="5dip"
            android:textSize="16sp"
            android:text="年龄:"  />
        <EditText android:id="@+id/et_age"
            android:layout_width="fill_parent"
            android:layout_height="40dip"
            android:layout_toRightOf="@id/tv_age_text"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@id/tv_age_text"
            android:hint="请输入年龄"
            android:paddingLeft="20dip"
            android:maxLength="3"
            android:inputType="number"
            android:background="@drawable/shape_edit"/>
        <TextView android:id="@+id/tv_sex_text"
            android:layout_width="80dip"
            android:layout_height="40dip"
            android:gravity="center_vertical|right"
            android:layout_below="@id/tv_age_text"
            android:layout_alignLeft="@id/tv_age_text"
            android:layout_marginRight="5dip"
            android:layout_marginBottom="5dip"
            android:text="性别:"
            android:textSize="16sp"  />
        <RadioGroup
            android:id="@+id/rg_sex"
            android:layout_width="fill_parent"
            android:layout_height="40dip"
            android:orientation="horizontal"
            android:layout_toRightOf="@id/tv_sex_text"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@id/tv_sex_text"   >
            <RadioButton
                android:id="@+id/rb_sex_male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text=""
                android:textSize="16sp"  />
            <RadioButton android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=""
                android:id="@+id/rb_sex_female"
                android:layout_weight="1"
                android:textSize="16sp">
            </RadioButton>
        </RadioGroup>
        <TextView android:id="@+id/tv_likes_text"
            android:layout_width="80dip"
            android:layout_height="40dip"
            android:gravity="center_vertical|right"
            android:layout_below="@id/rg_sex"
            android:layout_alignLeft="@id/tv_sex_text"
            android:layout_marginRight="5dip"
            android:layout_marginBottom="5dip"
            android:text="专业:"
            android:textSize="16sp"  />
        <CheckBox android:id="@+id/box1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/tv_likes_text"
            android:layout_below="@+id/rg_sex"
            android:text="@string/box1" ></CheckBox>
        <CheckBox android:id="@+id/box2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/box1"
            android:layout_below="@+id/rg_sex"
            android:text="@string/box2">

        </CheckBox>
        <CheckBox  android:id="@+id/box3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/box2"
            android:layout_below="@+id/rg_sex"
            android:text="@string/box3"  >
        </CheckBox>
        <TextView android:id="@+id/tv_phone_text"
            android:layout_width="80dip"
            android:layout_height="40dip"
            android:gravity="center_vertical|right"
            android:layout_marginRight="5dip"
            android:layout_below="@id/tv_likes_text"
            android:layout_marginBottom="5dip"
            android:textSize="16sp"
            android:text="联系电话:"  />
        <EditText android:id="@+id/et_phone"
            android:layout_width="fill_parent"
            android:layout_height="40dip"
            android:layout_toRightOf="@id/tv_phone_text"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@id/tv_phone_text"
            android:hint="请输入手机号"
            android:paddingLeft="20dip"
            android:inputType="phone"
            android:maxLength="11"
            android:background="@drawable/shape_edit"/>
        <TextView android:id="@+id/tv_traindate_text"
            android:layout_width="80dip"
            android:layout_height="40dip"
            android:gravity="center_vertical|right"
            android:layout_marginRight="5dip"
            android:layout_below="@id/tv_phone_text"
            android:layout_marginBottom="5dip"
            android:textSize="16sp"
            android:text="入学日期"    />
        <EditText android:id="@+id/et_traindate"
            android:layout_width="fill_parent"
            android:layout_height="40dip"
            android:layout_toRightOf="@id/tv_traindate_text"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@id/tv_traindate_text"
            android:hint="点击选择日期"
            android:inputType="date"
            android:paddingLeft="20dip"
            android:focusable="false"
            android:background="@drawable/shape_edit"/>
        <Button android:id="@+id/btn_save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="18dp"
            android:text="保存"
            android:layout_below="@id/tv_traindate_text"
            android:layout_alignRight="@id/rg_sex"
            android:textColor="#ffffff"
            android:textSize="15sp"
            android:background="@drawable/shape_button">
        </Button>
        <Button android:id="@+id/btn_clear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="重置"
            android:layout_below="@id/tv_traindate_text"
            android:layout_toLeftOf="@id/btn_save"
            android:layout_marginRight="10dip"
            android:layout_marginTop="18dp"
            android:textColor="#ffffff"
            android:textSize="15sp"
            android:background="@drawable/shape_button">
        </Button>
    </RelativeLayout>
</ScrollView>
  1. 创建activity,命名为activity_search.xml,用于查询学生信息,相应.java文件见后文;
    在这里插入图片描述

activity_search.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
   >
    <EditText
        android:id="@+id/et_srarch"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:hint="请输入学员姓名"
        android:inputType="textPersonName"
        android:background="@drawable/shape_edit"/>
    <Button
        android:id="@+id/bn_sure_search"
        android:gravity="center"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="确定"
        android:textColor="#ffffff"
        android:textSize="18sp"
        android:background="@drawable/shape_button"/>
    <Button
        android:id="@+id/bn_return"
        android:gravity="center"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="返回"
        android:textColor="#ffffff"
        android:textSize="18sp"
        android:background="@drawable/shape_button"/>
    <LinearLayout
        android:id="@+id/linersearch"
        android:orientation="vertical"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="ID    姓 名    年 龄   性 别    专 业    电 话    日 期"
            android:textSize="15dp"
            android:textColor="#ff3300"
            />
        <ListView
            android:id="@+id/searchListView"
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            />
        <Button
            android:id="@+id/return_id"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="返回"
            android:textSize="15dp"
            android:textColor="#ffffff"
            android:background="@drawable/shape_button"/>
    </LinearLayout>
</LinearLayout>
  1. 自定义find_student_list_item.xml,用于查询时显示格式
    在这里插入图片描述

find_student_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    >
    <TextView android:id="@+id/tv_stu_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <TextView android:id="@+id/tv_stu_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <TextView android:id="@+id/tv_stu_age"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <TextView android:id="@+id/tv_stu_sex"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <TextView android:id="@+id/tv_stu_likes"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <TextView android:id="@+id/tv_stu_phone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <TextView android:id="@+id/tv_stu_traindate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
</LinearLayout>

3.2 java文件配置

在这里插入图片描述

1.MainActivity.java,可以查看数据库里的学生列表,通过button触发“增删改查”的操作;

package com.example.cungu.sqlitedemo;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity implements View.OnClickListener,
        AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    private static final String TAG = "TestSQLite";
    private Button addStudent;
    private Cursor cursor;
    private SimpleCursorAdapter adapter;
    private ListView listView;
    private List<Long> list;
    private RelativeLayout relativeLayout;
    private Button searchButton;
    private Button selectButton;
    private Button deleteButton;
    private Button selectAllButton;
    private Button canleButton;
    private LinearLayout layout;
    private StudentDao dao;
    private Student student;
    private Boolean isDeleteList = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e(TAG, "onCreate");
        list = new ArrayList<Long>();
        student = new Student();
        dao = new StudentDao(new StudentDBHelper(this));
        addStudent = (Button) findViewById(R.id.btn_add_student);
        searchButton = (Button) findViewById(R.id.bn_search_id);
        selectButton = (Button) findViewById(R.id.bn_select);
        deleteButton = (Button) findViewById(R.id.bn_delete);
        selectAllButton = (Button) findViewById(R.id.bn_selectall);
        canleButton = (Button) findViewById(R.id.bn_canel);
        layout = (LinearLayout) findViewById(R.id.showLiner);
        relativeLayout=(RelativeLayout) findViewById(R.id.RelativeLayout);
        listView = getListView();

        // 为按键设置监听
        addStudent.setOnClickListener(this);
        searchButton.setOnClickListener(this);
        selectButton.setOnClickListener(this);
        deleteButton.setOnClickListener(this);
        canleButton.setOnClickListener(this);
        selectAllButton.setOnClickListener(this);
        listView.setOnItemClickListener(this);
        listView.setOnItemLongClickListener(this);
        listView.setOnCreateContextMenuListener(this);

    }

    // 调用load()方法将数据库中的所有记录显示在当前页面
    @Override
    protected void onStart() {
        super.onStart();
        load();

    }

    public void onClick(View v) {
        // 跳转到添加信息的界面
        if (v == addStudent) {
            startActivity(new Intent(this,add_student.class));
        } else if (v == searchButton) {
            // 跳转到查询界面
            startActivity(new Intent(this, search.class));
        } else if (v == selectButton) {
            // 跳转到选择界面
            isDeleteList = !isDeleteList;
            if (isDeleteList) {
                checkOrClearAllCheckboxs(true);
            } else {
                showOrHiddenCheckBoxs(false);
            }
        } else if (v == deleteButton) {
            // 删除数据
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    long id = list.get(i);
                    Log.e(TAG, "delete id=" + id);
                    int count = dao.deleteStudentById(id);
                }
                dao.closeDB();
                load();
            }
        } else if (v == canleButton) {
            // 点击取消,回到初始界面
            load();
            layout.setVisibility(View.GONE);
            isDeleteList = !isDeleteList;
        } else if (v == selectAllButton) {
            // 全选,如果当前全选按钮显示是全选,则在点击后变为取消全选,如果当前为取消全选,则在点击后变为全选
            selectAllMethods();
        }
    }

    // 创建菜单
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        MenuInflater inflater = new MenuInflater(this); //getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
    }

    // 对菜单中的按钮添加响应时间
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        int item_id = item.getItemId();
        student = (Student) listView.getTag();
        Log.v(TAG, "TestSQLite++++student+" + listView.getTag() + "");
        final long student_id = student.getId();
        Intent intent = new Intent();
        Log.v(TAG, "TestSQLite+++++++id"+student_id);
        switch (item_id) {
   /* 添加
   case R.id.add:
    startActivity(new Intent(this, AddStudentActivity.class));
    break;*/
            // 删除
            case R.id.delete:
                deleteStudentInformation(student_id);
                break;
            case R.id.look:
                // 查看学生信息
                Log.v(TAG, "TestSQLite+++++++look"+student+"");
                intent.putExtra("student", student);
                intent.setClass(this, student_info.class);
                this.startActivity(intent);
                break;
            case R.id.write:
                // 修改学生信息
                intent.putExtra("student", student);
                intent.setClass(this, add_student.class);
                this.startActivity(intent);
                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
    {
        Student student = (Student) dao.getStudentFromView(view, id);
        listView.setTag(student);
        registerForContextMenu(listView);
        return false;
    }

    // 点击一条记录是触发的事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        if (!isDeleteList) {
            student = dao.getStudentFromView(view, id);
            Log.e(TAG, "student*****" + dao.getStudentFromView(view, id));
            Intent intent = new Intent();
            intent.putExtra("student", student);
            intent.setClass(this, student_info.class);
            this.startActivity(intent);
        } else {
            CheckBox box = (CheckBox) view.findViewById(R.id.cb_box);
            box.setChecked(!box.isChecked());
            list.add(id);
            deleteButton.setEnabled(box.isChecked());
        }
    }

    // 自定义一个加载数据库中的全部记录到当前页面的无参方法
    public void load() {
        StudentDBHelper studentDBHelper = new StudentDBHelper(this);
        SQLiteDatabase database = studentDBHelper.getWritableDatabase();
        cursor = database.query(TableContanst.STUDENT_TABLE, null, null, null,
                null, null, TableContanst.StudentColumns.MODIFY_TIME + " desc");
        startManagingCursor(cursor);
        adapter = new SimpleCursorAdapter(this, R.layout.student_list_item,
                cursor, new String[] { TableContanst.StudentColumns.ID,
                TableContanst.StudentColumns.NAME,
                TableContanst.StudentColumns.AGE,
                TableContanst.StudentColumns.SEX,
                TableContanst.StudentColumns.LIKES,
                TableContanst.StudentColumns.PHONE_NUMBER,
                TableContanst.StudentColumns.TRAIN_DATE }, new int[] {
                R.id.tv_stu_id, R.id.tv_stu_name, R.id.tv_stu_age,
                R.id.tv_stu_sex, R.id.tv_stu_likes, R.id.tv_stu_phone,
                R.id.tv_stu_traindate });
        listView.setAdapter(adapter);
    }

    // 全选或者取消全选
    private void checkOrClearAllCheckboxs(boolean b) {
        int childCount = listView.getChildCount();
        Log.e(TAG, "list child size=" + childCount);
        for (int i = 0; i < childCount; i++) {
            View view = listView.getChildAt(i);
            if (view != null) {
                CheckBox box = (CheckBox) view.findViewById(R.id.cb_box);
                box.setChecked(!b);
            }
        }
        showOrHiddenCheckBoxs(true);
    }

    // 显示或者隐藏自定义菜单
    private void showOrHiddenCheckBoxs(boolean b) {
        int childCount = listView.getChildCount();
        Log.e(TAG, "list child size=" + childCount);
        for (int i = 0; i < childCount; i++) {
            View view = listView.getChildAt(i);
            if (view != null) {
                CheckBox box = (CheckBox) view.findViewById(R.id.cb_box);
                int visible = b ? View.VISIBLE : View.GONE;
                box.setVisibility(visible);
                layout.setVisibility(visible);
                deleteButton.setEnabled(false);
            }
        }
    }

    // 自定义一个利用对话框形式进行数据的删除

    private void deleteStudentInformation(final long delete_id) {
        // 利用对话框的形式删除数据
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("学员信息删除")
                .setMessage("确定删除所选记录?")
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        int raws = dao.deleteStudentById(delete_id);
                        layout.setVisibility(View.GONE);
                        isDeleteList = !isDeleteList;
                        load();
                        if (raws > 0) {
                            Toast.makeText(MainActivity.this, "删除成功!",Toast.LENGTH_LONG).show();
                        } else
                            Toast.makeText(MainActivity.this, "删除失败!",Toast.LENGTH_LONG).show();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    // 点击全选事件时所触发的响应
    private void selectAllMethods() {
        // 全选,如果当前全选按钮显示是全选,则在点击后变为取消全选,如果当前为取消全选,则在点击后变为全选
        if (selectAllButton.getText().toString().equals("全选")) {
            int childCount = listView.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View view = listView.getChildAt(i);
                if (view != null) {
                    CheckBox box = (CheckBox) view.findViewById(R.id.cb_box);
                    box.setChecked(true);
                    deleteButton.setEnabled(true);
                    selectAllButton.setText("取消全选");
                }
            }
        } else if (selectAllButton.getText().toString().equals("取消全选")) {
            checkOrClearAllCheckboxs(true);
            deleteButton.setEnabled(false);
            selectAllButton.setText("全选");
        }
    }
}
  1. student_info.java,显示一个学生的详细信息;
package com.example.cungu.sqlitedemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class student_info extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_info);
        Intent intent = getIntent();
        Student student = (Student) intent.getSerializableExtra(TableContanst.STUDENT_TABLE);
        ((TextView)findViewById(R.id.tv_info_id)).setText(student.getId()+"");
        ((TextView)findViewById(R.id.tv_info_name)).setText(student.getName());
        ((TextView)findViewById(R.id.tv_info_age)).setText(student.getAge()+"");
        ((TextView)findViewById(R.id.tv_info_sex)).setText(student.getSex());
        ((TextView)findViewById(R.id.tv_info_likes)).setText(student.getLike());
        ((TextView)findViewById(R.id.tv_info_train_date)).setText(student.getTrainDate());
        ((TextView)findViewById(R.id.tv_info_phone)).setText(student.getPhoneNumber());

    }
    public void goBack(View view) {
        finish();
    }
}
  1. add_student.java,添加学生;
package com.example.cungu.sqlitedemo;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

public class add_student extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "AddStudentActivity";
    private final static int DATE_DIALOG = 1;
    private static final int DATE_PICKER_ID = 1;
    private TextView idText;
    private EditText nameText;
    private EditText ageText;
    private EditText phoneText;
    private EditText dataText;
    private RadioGroup group;
    private RadioButton button1;
    private RadioButton button2;
    private CheckBox box1;
    private CheckBox box2;
    private CheckBox box3;
    private Button restoreButton;
    private String sex;
    private Button resetButton;
    private Long student_id;
    private StudentDao dao;
    private boolean isAdd = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_student);
        idText = (TextView) findViewById(R.id.tv_stu_id);
        nameText = (EditText) findViewById(R.id.et_name);
        ageText = (EditText) findViewById(R.id.et_age);
        button1 = (RadioButton) findViewById(R.id.rb_sex_female);
        button2 = (RadioButton) findViewById(R.id.rb_sex_male);
        phoneText = (EditText) findViewById(R.id.et_phone);
        dataText = (EditText) findViewById(R.id.et_traindate);
        group = (RadioGroup) findViewById(R.id.rg_sex);
        box1 = (CheckBox) findViewById(R.id.box1);
        box2 = (CheckBox) findViewById(R.id.box2);
        box3 = (CheckBox) findViewById(R.id.box3);
        restoreButton = (Button) findViewById(R.id.btn_save);
        resetButton = (Button) findViewById(R.id.btn_clear);
        dao = new StudentDao(new StudentDBHelper(this)); // 设置监听 78
        restoreButton.setOnClickListener(this);
        resetButton.setOnClickListener(this);
        dataText.setOnClickListener(this);
        checkIsAddStudent();
    }
    // 检查此时Activity是否用于添加学员信息
    private void checkIsAddStudent() {
        Intent intent = getIntent();
        Serializable serial = intent.getSerializableExtra(TableContanst.STUDENT_TABLE);
        if (serial == null) {
            isAdd = true;
            dataText.setText(getCurrentDate());
        } else {
            isAdd = false;
            Student s = (Student) serial;
            showEditUI(s);
        }
    }
    //显示学员信息更新的UI104
    private void showEditUI(Student student) {
        // 先将Student携带的数据还原到student的每一个属性中去
        student_id = student.getId();
        String name = student.getName();
        int age = student.getAge();
        String phone = student.getPhoneNumber();
        String data = student.getTrainDate();
        String like = student.getLike();
        String sex = student.getSex();
        if (sex.toString().equals("男")) {
            button2.setChecked(true);
        } else if (sex.toString().equals("女")) {
            button1.setChecked(true);
        }
        if (like != null && !"".equals(like)) {
            if (box1.getText().toString().indexOf(like) >= 0) {
                box1.setChecked(true);
            }
            if (box2.getText().toString().indexOf(like) >= 0) {
                box2.setChecked(true);
            }
            if (box3.getText().toString().indexOf(like) >= 0) {
                box3.setChecked(true);
            }
        }
        // 还原数据
        idText.setText(student_id + "");
        nameText.setText(name + "");
        ageText.setText(age + "");
        phoneText.setText(phone + "");
        dataText.setText(data + "");
        setTitle("学员信息更新");
        restoreButton.setText("更新");
    }
    public void onClick(View v) {
        // 收集数据
        if (v == restoreButton) {
            if (!checkUIInput()) {// 界面输入验证
                return;
            }
            Student student = getStudentFromUI();
            if (isAdd) {
                long id = dao.addStudent(student);
                dao.closeDB();
                if (id > 0) {
                    Toast.makeText(this, "保存成功, ID=" + id,Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(this, "保存失败,请重新输入!", Toast.LENGTH_SHORT).show();
                }
            } else if (!isAdd) {
                long id = dao.addStudent(student);
                dao.closeDB();
                if (id > 0) {
                    Toast.makeText(this, "更新成功",Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(this, "更新失败,请重新输入!",Toast.LENGTH_SHORT).show();
                }
            }
        } else if (v == resetButton) {
            clearUIData();
        } else if (v == dataText) {
            showDialog(DATE_PICKER_ID);
        }
    }
    //  清空界面的数据176
    private void clearUIData() {
        nameText.setText("");
        ageText.setText("");
        phoneText.setText("");
        dataText.setText("");
        box1.setChecked(false);
        box2.setChecked(false);
        group.clearCheck();
    }
    //  收集界面输入的数据,并将封装成Student对象
    private Student getStudentFromUI() {
        String name = nameText.getText().toString();
        int age = Integer.parseInt(ageText.getText().toString());
        String sex = ((RadioButton) findViewById(group.getCheckedRadioButtonId())).getText().toString();
        String likes = "";
        if (box1.isChecked()) { // basketball, football football
            likes += box1.getText();
        }
        if (box2.isChecked()) {
            if (likes.equals("")) {
                likes += box2.getText();
            } else {
                likes += "," + box2.getText();
            }
            if (likes.equals("")) {
                likes += box3.getText();
            } else {
                likes += "," + box3.getText();
            }
        }
        String trainDate = dataText.getText().toString();
        String phoneNumber = phoneText.getText().toString();
        String modifyDateTime = getCurrentDateTime();
        Student s=new Student(name, age, sex, likes, phoneNumber, trainDate,
                modifyDateTime);
        if (!isAdd) {
            s.setId(Integer.parseInt(idText.getText().toString()));
            dao.deleteStudentById(student_id);
        }
        return s;
    }
    //  * 得到当前的日期时间
    private String getCurrentDateTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format.format(new Date());
    }
    //  * 得到当前的日期
    private String getCurrentDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date());
    }
    //验证用户是否按要求输入了数据
    private boolean checkUIInput() { // name, age, sex
        String name = nameText.getText().toString();
        String age = ageText.getText().toString();
        int id = group.getCheckedRadioButtonId();
        String message = null;
        View invadView = null;
        if (name.trim().length() == 0) {
            message = "请输入姓名!";
            invadView = nameText;
        } else if (age.trim().length() == 0) {
            message = "请输入年龄!";
            invadView = ageText;
        } else if (id == -1) {
            message = "请选择性别!";
        }
        if (message != null) {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
            if (invadView != null)
                invadView.requestFocus();
            return false;
        }   return true;  }
    //时间的监听与事件
    private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener()
    {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            dataText.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
        }
    };
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_PICKER_ID:
                return new DatePickerDialog(this, onDateSetListener, 2016, 9, 10);
        }
        return null;
    }
}
  1. search.java,从数据库获取学生信息;
package com.example.cungu.sqlitedemo;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class search extends AppCompatActivity implements View.OnClickListener{
    private EditText nameText;
    private Button button;
    private Button reButton;
    private Cursor cursor;
    private SimpleCursorAdapter adapter;
    private ListView listView;
    private StudentDao dao;
    private Button returnButton;
    private LinearLayout layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        nameText = (EditText) findViewById(R.id.et_srarch);
        layout=(LinearLayout) findViewById(R.id.linersearch);
        button = (Button) findViewById(R.id.bn_sure_search);
        reButton = (Button) findViewById(R.id.bn_return);
        listView = (ListView) findViewById(R.id.searchListView);
        returnButton = (Button) findViewById(R.id.return_id);
        dao = new StudentDao(new StudentDBHelper(this));


        reButton.setOnClickListener(this);
        returnButton.setOnClickListener(this);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == button) {
            reButton.setVisibility(View.GONE);
            button.setVisibility(View.GONE);
            nameText.setVisibility(View.GONE);
            layout.setVisibility(View.VISIBLE);
            String name = nameText.getText().toString();
            cursor = dao.findStudent(name);
            if (!cursor.moveToFirst()) {
                Toast.makeText(this, "没有所查学员信息!", Toast.LENGTH_SHORT).show();
            } else
                //如果有所查询的信息,则将查询结果显示出来
                adapter = new SimpleCursorAdapter(this, R.layout.find_student_list_item,
                        cursor, new String[] { TableContanst.StudentColumns.ID,
                        TableContanst.StudentColumns.NAME,
                        TableContanst.StudentColumns.AGE,
                        TableContanst.StudentColumns.SEX,
                        TableContanst.StudentColumns.LIKES,
                        TableContanst.StudentColumns.PHONE_NUMBER,
                        TableContanst.StudentColumns.TRAIN_DATE },
                        new int[] {
                                R.id.tv_stu_id,
                                R.id.tv_stu_name,
                                R.id.tv_stu_age,
                                R.id.tv_stu_sex,
                                R.id.tv_stu_likes,
                                R.id.tv_stu_phone,
                                R.id.tv_stu_traindate });
            listView.setAdapter(adapter);
        }else if(v==reButton|v==returnButton){
            finish();
        }
    }
}
  1. 自定义类StudentDao.java,用于封装对数据库增删改查操作函数;
package com.example.cungu.sqlitedemo;

import com.example.cungu.sqlitedemo.StudentDBHelper;
import com.example.cungu.sqlitedemo.TableContanst;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.example.cungu.sqlitedemo.Student;

public class StudentDao {
    private StudentDBHelper dbHelper;
    private Cursor cursor;
    public StudentDao(StudentDBHelper dbHelper) {
        this.dbHelper = dbHelper;
    }
    // 添加一个Student对象数据到数据库表
    public long addStudent(Student s) {
        ContentValues values = new ContentValues();
        values.put(TableContanst.StudentColumns.NAME, s.getName());
        values.put(TableContanst.StudentColumns.AGE, s.getAge());
        values.put(TableContanst.StudentColumns.SEX, s.getSex());
        values.put(TableContanst.StudentColumns.LIKES, s.getLike());
        values.put(TableContanst.StudentColumns.PHONE_NUMBER, s.getPhoneNumber());
        values.put(TableContanst.StudentColumns.TRAIN_DATE, s.getTrainDate());
        values.put(TableContanst.StudentColumns.MODIFY_TIME, s.getModifyDateTime());
        return dbHelper.getWritableDatabase().insert(TableContanst.STUDENT_TABLE, null, values);
    }

    // 删除一个id所对应的数据库表student的记录
    public int deleteStudentById(long id) {
        return dbHelper.getWritableDatabase().delete(TableContanst.STUDENT_TABLE,
                TableContanst.StudentColumns.ID + "=?", new String[] { id + "" });
    }

    // 更新一个id所对应数据库表student的记录
    public int updateStudent(Student s) {
        ContentValues values = new ContentValues();
        values.put(TableContanst.StudentColumns.NAME, s.getName());
        values.put(TableContanst.StudentColumns.AGE, s.getAge());
        values.put(TableContanst.StudentColumns.SEX, s.getSex());
        values.put(TableContanst.StudentColumns.LIKES, s.getLike());
        values.put(TableContanst.StudentColumns.PHONE_NUMBER, s.getPhoneNumber());
        values.put(TableContanst.StudentColumns.TRAIN_DATE, s.getTrainDate());
        values.put(TableContanst.StudentColumns.MODIFY_TIME, s.getModifyDateTime());
        return dbHelper.getWritableDatabase().update(TableContanst.STUDENT_TABLE, values,
                TableContanst.StudentColumns.ID + "=?", new String[] { s.getId() + "" });
    }
    // 查询所有的记录
    public List<Map<String,Object>> getAllStudents() {
        //modify_time desc
        List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
        Cursor cursor = dbHelper.getWritableDatabase().query(TableContanst.STUDENT_TABLE, null, null, null,
                null, null, TableContanst.StudentColumns.MODIFY_TIME+" desc");
        while(cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<String, Object>(8);
            long id = cursor.getInt(cursor.getColumnIndex(TableContanst.StudentColumns.ID));
            map.put(TableContanst.StudentColumns.ID, id);
            String name = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.NAME));
            map.put(TableContanst.StudentColumns.NAME, name);
            int age = cursor.getInt(cursor.getColumnIndex(TableContanst.StudentColumns.AGE));
            map.put(TableContanst.StudentColumns.AGE, age);
            String sex = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.SEX));
            map.put(TableContanst.StudentColumns.SEX, sex);
            String likes = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.LIKES));
            map.put(TableContanst.StudentColumns.LIKES, likes);
            String phone_number = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.PHONE_NUMBER));
            map.put(TableContanst.StudentColumns.PHONE_NUMBER, phone_number);
            String train_date = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.TRAIN_DATE));
            map.put(TableContanst.StudentColumns.TRAIN_DATE, train_date);
            String modify_time = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.MODIFY_TIME));
            map.put(TableContanst.StudentColumns.MODIFY_TIME, modify_time);
            data.add(map);
        }
        return data;
    }
    //模糊查询一条记录
    public Cursor findStudent(String name){
        Cursor cursor = dbHelper.getWritableDatabase().query(TableContanst.STUDENT_TABLE, null, "name like ?",
                new String[] { "%" + name + "%" }, null, null, null,null);
        return cursor;  }
    //按姓名进行排序
    public Cursor sortByName(){
        Cursor cursor = dbHelper.getWritableDatabase().query(TableContanst.STUDENT_TABLE, null,null,
                null, null, null,TableContanst.StudentColumns.NAME);
        return cursor;  }
    //按入学日期进行排序
    public Cursor sortByTrainDate(){
        Cursor cursor = dbHelper.getWritableDatabase().query(TableContanst.STUDENT_TABLE, null,null,
                null, null, null,TableContanst.StudentColumns.TRAIN_DATE);
        return cursor;
    }
    //按学号进行排序
    public Cursor sortByID(){
        Cursor cursor = dbHelper.getWritableDatabase().query(TableContanst.STUDENT_TABLE, null,null,
                null, null, null,TableContanst.StudentColumns.ID);
        return cursor; }
    public void closeDB() {
        dbHelper.close();  } //自定义的方法通过View和Id得到一个student对象
    public Student getStudentFromView(View view, long id) {
        TextView nameView = (TextView) view.findViewById(R.id.tv_stu_name);
        TextView ageView = (TextView) view.findViewById(R.id.tv_stu_age);
        TextView sexView = (TextView) view.findViewById(R.id.tv_stu_sex);
        TextView likeView = (TextView) view.findViewById(R.id.tv_stu_likes);
        TextView phoneView = (TextView) view.findViewById(R.id.tv_stu_phone);
        TextView dataView = (TextView) view.findViewById(R.id.tv_stu_traindate);
        String name = nameView.getText().toString();
        int age = Integer.parseInt(ageView.getText().toString());
        String sex = sexView.getText().toString();
        String like = likeView.getText().toString();
        String phone = phoneView.getText().toString();
        String data = dataView.getText().toString();
        Student student = new Student(id, name, age, sex, like, phone, data,null);
        return student;
    }
}
  1. StudentDBHelper.java
package com.example.cungu.sqlitedemo;

import com.example.cungu.sqlitedemo.TableContanst;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class StudentDBHelper extends SQLiteOpenHelper {
    private static final String TAG = "StudentDBHelper";
    public static final String DB_NAME = "student_manager.db";
    public static final int VERSION = 1; //构造方法
    public StudentDBHelper(Context context, String name, CursorFactory factory, int version)
    {
        super(context, name, factory, version);
    }
    public StudentDBHelper(Context context) {
        this(context, DB_NAME, null, VERSION);  }

    //创建数据库
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.v(TAG, "onCreate");
        db.execSQL("create table "
                + TableContanst.STUDENT_TABLE     + "(_id Integer primary key AUTOINCREMENT,"
                + "name char,age integer, sex char, likes char, phone_number char,train_date date, "
                + "modify_time DATETIME)");  }
    //更新数据库
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.v(TAG, "onUpgrade");
    }
}
  1. 自定义类Student.java,用于封装student对象,从数据库中获得值;
package com.example.cungu.sqlitedemo;

import java.io.Serializable;
import android.view.View;
import android.widget.TextView;
public class Student implements Serializable{
    private long id;
    private String name;
    private int age;
    private String sex;
    private String like;
    private String phoneNumber;
    private String trainDate;
    private String modifyDateTime;
    public Student() {
        super();
    }
    public Student(long id, String name, int age, String sex, String like, String phoneNumber,
                   String trainDate, String modifyDateTime) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.like = like;
        this.phoneNumber = phoneNumber;
        this.trainDate = trainDate;
        this.modifyDateTime = modifyDateTime;
    }
    public Student(String name, int age, String sex, String like, String phoneNumber,
                   String trainDate, String modifyDateTime) {
        super();
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.like = like;
        this.phoneNumber = phoneNumber;
        this.trainDate = trainDate;
        this.modifyDateTime = modifyDateTime;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    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 getSex() {
        return sex;  }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getLike() {
        return like;
    }
    public void setLike(String like) {
        this.like = like;
    }
    public String getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;  }
    public String getTrainDate() {
        return trainDate;
    }
    public void setTrainDate(String trainDate) {
        this.trainDate = trainDate;
    }
    public String getModifyDateTime() {
        return modifyDateTime;
    }
    public void setModifyDateTime(String modifyDateTime) {
        this.modifyDateTime = modifyDateTime;
    }
}

8.自定义类 TableContanst.java,用于连接表:

package com.example.cungu.sqlitedemo;

public final class TableContanst {

    public static final String STUDENT_TABLE = "student";

    public static final class StudentColumns {
        public static final String ID = "_id";
        public static final String NAME = "name";
        public static final String AGE = "age";
        public static final String SEX = "sex";
        public static final String LIKES = "likes";
        public static final String PHONE_NUMBER = "phone_number";
        public static final String TRAIN_DATE = "train_date";
        public static final String MODIFY_TIME = "modify_time";
    }
}

3.3 界面美化

引入图片和3种样式:
在这里插入图片描述在这里插入图片描述
在这里插入图片描述在这里插入图片描述
可以根据自己想法,自定义,下面给出我残次的参考样式:

  • shape_button.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- 形状 -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:shape="rectangle"
    tools:ignore="MissingDefaultResource">

    <solid android:color="#a1afc9" />
    <!-- 边框 -->
    <stroke
        android:width="1dip"
        android:color="#ffffff" />
    <!-- 内填充颜色 -->
    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />
    <!-- 圆角 -->
    <corners android:radius="200dp" />
</shape>
  • shape_button_white.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- 形状 -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:shape="rectangle"
    tools:ignore="MissingDefaultResource">

    <solid android:color="#ffffff" />
    <!-- 边框 -->
    <stroke
        android:width="1dip"
        android:color="#a1afc9" />
    <!-- 内填充颜色 -->
    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />
    <!-- 圆角 -->
    <corners android:radius="200dp" />
</shape>
  • shape_edit.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- 形状 -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="#ffffff" />
    <!-- 边框 -->
    <stroke
        android:width="1dip"
        android:color="#ffffff" />
    <!-- 内填充颜色 -->
    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />
    <!-- 圆角 -->
    <corners android:radius="6dp" />
</shape>

项目大致如此~
总结:

  1. 残次的UI真是分分钟想我想停掉手中的项目,强迫症星人一定要给自己美化哦~
  2. 项目中全选部分和给学生分配序号有待完善。

温馨提示:
如果每次调试安装没有手动卸载APP,数据库中的内容不会自动删除哦!好比如:之前创建了3个学生,即使全选删除了;未卸载之前的APP,直接第二次调试程序重装之后,创建学生,学生编号不会从1开始。所以,最好是手动卸载之前的APP、再重新安装哦!

猜你喜欢

转载自blog.csdn.net/cungudafa/article/details/84726168