学生信息管理系统android_android学生管理系统 - CSDN
  • 百度上流传最广的版本有所欠缺,并不能直接使用,同时有很多不必要的功能,这是我进行删减、修改、核查后的版本,根据下面的步骤一步步来直接能够运行程序。

    百度上流传最广的版本有所欠缺,并不能直接使用,同时有很多不必要的功能,这是我进行删减、修改、核查后的版本,根据下面的步骤一步步来直接能够运行程序。

    本程序实现的功能是增删改查以及全选

    首先是程序提纲

    主要部分是java文件和xml文件。

    activity放在java文件里面,xml文件就是布局文件,用来规定界面的显示格式。

    主要的活动 java xml 备注
    1 StudentListActivity main.xml 除数据外的布局
    student_list_item.xml 数据的布局
    2 menu.xml 上下文菜单 ContextMenu
    3 ShowStudentActivity student_info.xml 单条记录的详细信息
    4 AddStudentActivity add_student.xml 添加记录
    5 StudentSearch search.xml 查找记录,除数据外的布局
    find_student_list_item.xml 查找到的记录的布局

    类定义的Java文件

    • StudentDao
    • StudnetDBHelper
    • Student
    • TableContanst

    其他文件

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

    下面看看我的文件目录

    文件目录1

    文件目录2

    值得注意的是,menu.xml不是放在layout目录下,而是放在menu目录下。

    然后依次介绍各个activity的代码

    主界面是StudentListActivity

    代码如下

    java文件:StudentListActivity

    package com.example.asus.student;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    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.os.Bundle;
    import android.util.Log;
    import android.view.ContextMenu;
    import android.view.ContextMenu.ContextMenuInfo;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.AdapterView.OnItemLongClickListener;
    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 StudentDBHelper.StudentDBHelper;
    import Student.Student;
    //import AddStudentActivity;
    import TableContanst.TableContanst;
    
    public class StudentListActivity extends ListActivity implements
            OnClickListener, OnItemClickListener, 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.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(StudentListActivity.this, AddStudentActivity.class));
            } else if (v == searchButton) {
                // 跳转到查询界面
                startActivity(new Intent(this, StudentSearch.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, 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, ShowStudentActivity.class);
                    this.startActivity(intent);
                    break;
                case R.id.write:
                    // 修改学生信息
                    intent.putExtra("student", student);
                    intent.setClass(this, AddStudentActivity.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, ShowStudentActivity.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(
                    StudentListActivity.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(StudentListActivity.this, "删除成功!",
                                        Toast.LENGTH_LONG).show();
                            } else
                                Toast.makeText(StudentListActivity.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("全选");
            }
        }
    }

    布局文件:main.xml和student_list_item.xml

    代码如下

    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">
            <Button android:id="@+id/bn_search_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="搜索"
                android:gravity="center_vertical" />
            <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" />
            <Button  android:gravity="center_vertical"
                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"></Button>
        </RelativeLayout>
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="        ID            姓 名                年 龄         性 别        "
            />
    
        <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>
    

    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" />
        <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>
    

    展示单条记录详细信息的ShowStudentActivity

    代码如下

    java文件:ShowStudentActivity

    package com.example.asus.student;
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;
    import Student.Student;
    import TableContanst.TableContanst;
    public class ShowStudentActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.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();
        }
    }
    

    布局文件: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:padding="5dip"       >
        <TextView android:id="@+id/id2_text_id"
            android:layout_width="80dip"
            android:layout_height="40dip"
            android:layout_marginRight="5dip"
            android:layout_marginTop="5dip"
            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="5dip"
            android:layout_marginBottom="5dip"
            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="5dip"
            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="5dip"
            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="5dip"
            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="5dip"
            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:text="返回列表界面"
            android:layout_below="@id/train2_time_text_id"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:onClick="goBack">
        </Button>
    </RelativeLayout>
    

    添加记录的活动AddStudentActivity

    代码如下

    java文件:AddStudenActivity

    package com.example.asus.student;
    import java.io.Serializable;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.HashSet;
    import android.app.Activity;
    import android.app.DatePickerDialog;
    import android.app.Dialog;
    import android.content.ContentValues;
    import android.content.Intent;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.CompoundButton.OnCheckedChangeListener;
    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 StudentDBHelper.StudentDBHelper;
    import Student.Student;
    import TableContanst.TableContanst;
    public class AddStudentActivity extends Activity implements 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
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.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, 2011, 8, 14);
            }
            return null;
        }
    }
    

    布局文件: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:padding="5dip"      >
            <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_marginTop="5dip"
                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="请输入姓名,如liukenken"
                android:inputType="textPersonName"
                android:paddingLeft="20dip"/>
            <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"      />
            <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"     />
            <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"     />
            <Button android:id="@+id/btn_save"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="保存"
                android:layout_below="@id/tv_traindate_text"
                android:layout_alignRight="@id/rg_sex">
            </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">
            </Button>
        </RelativeLayout> </ScrollView>
    

    查找记录的活动StudentSearch

    代码如下

    java文件:StudentSearch

    package com.example.asus.student;
    import StudentDBHelper.StudentDBHelper;
    import TableContanst.TableContanst;
    import android.app.Activity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    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 StudentSearch extends Activity implements 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.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();
            }
        }
    }
    

    布局文件:search.xml和find_studetn_list_item.xml

    代码如下

    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" >
        <EditText
            android:id="@+id/et_srarch"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="请输入学员姓名"
            android:inputType="textPersonName" />
        <Button
            android:id="@+id/bn_sure_search"
            android:gravity="center"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="确定"         />
        <Button
            android:id="@+id/bn_return"
            android:gravity="center"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="返回"         />
        <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     姓 名     年 龄     性 别     爱 好     电 话     日 期"
                />
            <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="返回"     />
        </LinearLayout>
    </LinearLayout>
    

    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>

    主界面中跳出的上下文菜单ContextMenu的布局文件menu.xml

    <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>

    然后是一些自定义类的java文件

    StudentDao类

    java文件:StudentDao

    package com.example.asus.student;
    import StudentDBHelper.StudentDBHelper;
    import TableContanst.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 Student.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;
        }
    }

    StudentDBHelper类

    java文件:StudentDBHelper

    
    package StudentDBHelper;
    import TableContanst.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");
        }
    }
    

    Student类

    java文件:Student

    package Student;
    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;
        }
    }
    

    TableContanst类

    java文件:TableContanst

    package TableContanst;
    
    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";
        }
    }
    

    其他文件

    color.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="colorPrimary">#3F51B5</color>
        <color name="colorPrimaryDark">#303F9F</color>
        <color name="colorAccent">#EE82EE</color>
    </resources>
    

    strings.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <string name="hello">Hello World, TextStudentManager!</string>
        <string name="app_name">学员管理系统</string>
        <string name="information_write">学员信息修改</string>
        <string name="button1">男</string>
        <string name="button2">女</string>
        <string name="box1">唱歌</string>
        <string name="box2">跳舞</string>
        <string name="box3">健身</string>
        <string name="myButton">添加学员信息</string>
        <string name="spinner">请选择</string>
    </resources>

    styles.xml

    <resources>
    
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
        </style>
    
    </resources>
    

    AndroidManifest.xml

    再次提醒,所有自定义活动必须手动添加到这个文件中,包括设置主活动也是在此文件中

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.asus.student">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".StudentListActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:name=".AddStudentActivity">
            </activity>
            <activity android:name=".ShowStudentActivity">
            </activity>
            <activity android:name=".StudentSearch">
            </activity>
        </application>
    
    </manifest>

    最后是效果图片

    初始界面

    初始界面

    添加界面

    添加

    添加界面中的日历插件

    日历

    添加后返回主界面

    添加后返回主界面

    第一次打开的程序,ID是从1开始的,因为我之前有操作过,所以这里ID才不是从1开始的。

    单击记录后显示详细信息

    详细信息

    长按记录后跳出上下文菜单

    上下文菜单

    点击菜单中的删除按钮

    菜单中的删除

    删除后

    删除后

    下面看看多条记录的操作

    点击主界面的选择按钮

    主界面的选择

    点击全选按钮

    全选

    全选后删除

    删除后

    点击菜单中的修改按钮

    菜单中的修改

    搜索

    搜索

    搜索结果

    搜索结果

    以上就是关于我自己修改过的简易学生信息管理系统的全部说明,按照步骤来一步一步做,应该就能直接运。如果有问题的话,顶多就是改一下包的名字和gradle文件中版本号之类的一些简单的问题,具体需要结合电脑的实际情况来修改即可。

    欢迎指正。

    展开全文
  • 基于android学生信息管理系统,自己写来交了软工大作业,自建的sqlite数据库,里面有全部代码和开发文档
  • 这是一个教师管理学生信息的简单demo,主要是解析Excel表格,数据库的使用。有兴趣的可以下载并在此基础上做一些修改!
  • 利用ListView和数据库做一个学员信息管理系统。下面把做的代码复制下来,供大家参考。 首页的布局main.xml xml version="1.0" encoding="utf-8"?> LinearLayout xmlns:android=...

    利用ListView和数据库做一个学员信息管理系统。下面把做的代码复制下来,供大家参考。

    首页的布局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">
            <Button android:id="@+id/bn_search_id" 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" 
                android:text="搜索"
                android:gravity="center_vertical" />
            <Button android:gravity="center" 
                android:text="@string/myButton"
                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" />
            <Button  android:gravity="center_vertical"
                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"></Button>
        </RelativeLayout>
        <TextView 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="              ID            姓 名       年 龄         性 别        "
        />
        <ListView android:id="@android:id/list"
        android:layout_width="fill_parent" 
        android:layout_weight="1"
        android:layout_height="wrap_content"/>
        <LinearLayout 
            android:orientation="horizontal"
            android:id="@+id/showLiner"
            android:visibility="gone"    
             android:layout_width="fill_parent"
             android:layout_height="wrap_content">
             <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>
    复制代码

    创建listView中显示学员信息的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="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="@drawable/icon"/>
        <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>

      创建一个StudentListActivity做为主页显示学员信息以及进行一些操作。

    复制代码
    package cn.yj3g.student.activity;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    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.os.Bundle;
    import android.util.Log;
    import android.view.ContextMenu;
    import android.view.ContextMenu.ContextMenuInfo;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.AdapterView.OnItemLongClickListener;
    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 cn.yj3g.student.dao.StudentDao;
    import cn.yj3g.student.db.StudentDBHelper;
    import cn.yj3g.student.entry.Student;
    import cn.yj3g.student.entry.TableContanst;
    
    public class StudentListActivity extends ListActivity implements
            OnClickListener, OnItemClickListener, 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.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);
    
        }
    
        @Override
        protected void onStart() {
            // 调用load()方法将数据库中的所有记录显示在当前页面
            super.onStart();
            load();
    
        }
    
        public void onClick(View v) {
            // 跳转到添加信息的界面
            if (v == addStudent) {
                startActivity(new Intent(this, AddStudentActivity.class));
            } else if (v == searchButton) {
                // 跳转到查询界面
                startActivity(new Intent(this, StudentSearch.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();
            }
        }
        // 创建菜单
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v,
                ContextMenuInfo menuInfo) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.layout.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, ShowStudentActivity.class);
                this.startActivity(intent);
                break;
            case R.id.write:
                // 修改学生信息
                intent.putExtra("student", student);
                intent.setClass(this, AddStudentActivity.class);
                this.startActivity(intent);
                break;
            default:
                break;
            }
            return super.onContextItemSelected(item);
        }
    
        // 创建一个按钮菜单
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            menu.add(1, 1, 1, "按入学日期排序");
            menu.add(1, 2, 1, "按姓名进行排序");
            menu.add(1, 5, 1, "按学号进行排序");
            menu.add(1, 3, 1, "模糊查找");
            menu.add(1, 4, 1, "退出");
            return super.onCreateOptionsMenu(menu);
        }
    
        // 对菜单中的按钮添加响应时间
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            switch (id) {
            // 排序
            case 1:
                cursor = dao.sortByTrainDate();
                load(cursor);
                break;
    
            // 排序
            case 2:
                cursor = dao.sortByName();
                load(cursor);
                break;
            // 查找
            case 3:
                startActivity(new Intent(this, StudentSearch.class));
                break;
            // 退出
            case 4:
                finish();
                break;
            case 5:
                cursor = dao.sortByID();
                load(cursor);
                break;
            default:
                break;
            }
            return super.onOptionsItemSelected(item);
        }
    
        // 长点击一条记录触发的时间
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                int position, long id) {
            Student student = (Student) dao.getStudentFromView(view, id);
            listView.setTag(student);
            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, ShowStudentActivity.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(
                    StudentListActivity.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);
        }
    
        // 自定义一个加载数据库中的全部记录到当前页面的有参方法
        public void load(Cursor 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(StudentListActivity.this, "删除成功!",
                                        Toast.LENGTH_LONG).show();
                            } else
                                Toast.makeText(StudentListActivity.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("全选");
            }
        }
    }
    复制代码

    menu.xml文件

    复制代码
    1 <menu xmlns:android="http://schemas.android.com/apk/res/android">
    2 
    3     <group android:checkableBehavior="single">
    4         <item android:id="@+id/delete" android:title="删除学员信息" />
    5         <item android:id="@+id/look" android:title="详细信息" />
    6         <item android:id="@+id/add" android:title="添加学员信息" />
    7         <item android:id="@+id/write" android:title="修改学员信息" />
    8     </group>
    9 </menu>
    复制代码

    界面效果图如下:

    删除界面:

    在点击ListView中的一条Item时,老师要求显示出这个学生的详细信息,所以需要一个xml文件来显示这个信息。在这里我创建了一个student_info.xml文件

    复制代码
      1 <?xml version="1.0" encoding="utf-8"?>
      2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      3     android:orientation="vertical"
      4     android:layout_width="fill_parent"
      5     android:layout_height="fill_parent"
      6     android:padding="5dip"
      7     >
      8     <TextView android:id="@+id/id2_text_id"
      9         android:layout_width="80dip"
     10         android:layout_height="40dip"
     11         android:layout_marginRight="5dip"
     12         android:layout_marginTop="5dip"
     13         android:layout_marginBottom="5dip"
     14         android:textSize="16sp"
     15         android:gravity="left|center_vertical"
     16         android:text="学员ID:"
     17     />
     18     
     19     <TextView android:id="@+id/tv_info_id"
     20         android:layout_width="fill_parent"
     21         android:layout_height="40dip"
     22         android:layout_toRightOf="@id/id2_text_id"
     23         android:layout_alignParentRight="true"
     24         android:layout_alignTop="@id/id2_text_id"
     25         android:gravity="left|center_vertical"
     26     />
     27     
     28     <TextView android:id="@+id/name2_text_id"
     29         android:layout_width="80dip"
     30         android:layout_height="40dip"
     31         android:layout_marginRight="5dip"
     32         android:layout_marginTop="5dip"
     33         android:layout_marginBottom="5dip"
     34         android:layout_below="@id/id2_text_id"
     35         android:layout_alignLeft="@id/id2_text_id"
     36         android:textSize="16sp"
     37         android:gravity="left|center_vertical"
     38         android:text="姓名:"
     39     />
     40     
     41     <TextView android:id="@+id/tv_info_name"
     42         android:layout_width="fill_parent"
     43         android:layout_height="40dip"
     44         android:layout_toRightOf="@id/name2_text_id"
     45         android:layout_alignParentRight="true"
     46         android:layout_alignTop="@id/name2_text_id"
     47         android:gravity="left|center_vertical"
     48     />
     49     
     50     <TextView android:id="@+id/age2_text_id"
     51         android:layout_width="80dip"
     52         android:layout_height="40dip"
     53         android:gravity="left|center_vertical"
     54         android:layout_marginRight="5dip"
     55         android:layout_below="@id/name2_text_id"
     56         android:layout_marginBottom="5dip"
     57         android:textSize="16sp"
     58         android:text="年龄:"
     59     />
     60     
     61     <TextView android:id="@+id/tv_info_age"
     62         android:layout_width="fill_parent"
     63         android:layout_height="40dip"
     64         android:layout_toRightOf="@id/age2_text_id"
     65         android:layout_alignParentRight="true"
     66         android:layout_alignTop="@id/age2_text_id"
     67         android:gravity="left|center_vertical"
     68     />
     69     
     70     <TextView android:id="@+id/sex2_text_id"
     71         android:layout_width="80dip"
     72         android:layout_height="40dip"
     73         android:gravity="left|center_vertical"
     74         android:layout_below="@id/age2_text_id"
     75         android:layout_alignLeft="@id/age2_text_id"
     76         android:layout_marginRight="5dip"
     77         android:layout_marginBottom="5dip"
     78         android:text="性别:"
     79         android:textSize="16sp"
     80     />
     81     
     82     <TextView
     83         android:id="@+id/tv_info_sex"
     84         android:layout_width="fill_parent"
     85         android:layout_height="40dip"
     86         android:layout_toRightOf="@id/sex2_text_id"
     87         android:layout_alignParentRight="true"
     88         android:layout_alignTop="@id/sex2_text_id"
     89         android:gravity="left|center_vertical"
     90         />
     91     
     92     <TextView  android:id="@+id/like2_text_id"
     93         android:layout_width="80dip"
     94         android:layout_height="40dip"
     95         android:gravity="left|center_vertical"
     96         android:layout_below="@id/sex2_text_id"
     97         android:layout_alignLeft="@id/sex2_text_id"
     98         android:layout_marginRight="5dip"
     99         android:layout_marginBottom="5dip"
    100         android:text="爱好:"
    101         android:textSize="16sp"
    102     />
    103     <TextView android:layout_height="40dip" 
    104         android:id="@+id/tv_info_likes" 
    105         android:layout_width="wrap_content" 
    106         android:layout_toRightOf="@id/like2_text_id"
    107         android:layout_below="@id/sex2_text_id"
    108         android:layout_marginRight="52dip"
    109         android:gravity="left|center_vertical"/>
    110 
    111     <TextView android:id="@+id/contact2_text_id"
    112         android:layout_width="80dip"
    113         android:layout_height="40dip"
    114         android:gravity="center_vertical|left"
    115         android:layout_marginRight="5dip"
    116         android:layout_below="@id/like2_text_id"
    117         android:layout_marginBottom="5dip"
    118         android:textSize="16sp"
    119         android:text="联系电话:"
    120     />
    121     
    122     <TextView android:id="@+id/tv_info_phone"
    123         android:layout_width="fill_parent"
    124         android:layout_height="40dip"
    125         android:layout_toRightOf="@id/contact2_text_id"
    126         android:layout_alignParentRight="true"
    127         android:layout_alignTop="@id/contact2_text_id"
    128         android:gravity="center_vertical|left"
    129     />
    130     
    131     <TextView android:id="@+id/train2_time_text_id"
    132         android:layout_width="80dip"
    133         android:layout_height="40dip"
    134         android:gravity="center_vertical|left"
    135         android:layout_marginRight="5dip"
    136         android:layout_below="@id/contact2_text_id"
    137         android:layout_marginBottom="5dip"
    138         android:textSize="16sp"
    139         android:text="入学日期"
    140     />
    141     
    142     <TextView android:id="@+id/tv_info_train_date"
    143         android:layout_width="fill_parent"
    144         android:layout_height="40dip"
    145         android:layout_toRightOf="@id/train2_time_text_id"
    146         android:layout_alignParentRight="true"
    147         android:layout_alignTop="@id/train2_time_text_id"
    148         android:gravity="center_vertical|left"
    149     />
    150     
    151     <Button android:id="@+id/back_to_list_id" 
    152         android:layout_width="fill_parent" 
    153         android:layout_height="wrap_content" 
    154         android:text="返回列表界面" 
    155         android:layout_below="@id/train2_time_text_id" 
    156         android:layout_alignParentLeft="true"
    157         android:layout_alignParentRight="true"
    158         android:onClick="goBack">
    159     </Button>
    160 </RelativeLayout>
    复制代码

    当然我们需要一个Activity来显示这些信息,在这里我创建了一个ShowStudentActivity。

    复制代码
     1 package cn.yj3g.student.activity;
     2 
     3 import android.app.Activity;
     4 import android.content.Intent;
     5 import android.os.Bundle;
     6 import android.view.View;
     7 import android.widget.TextView;
     8 import cn.yj3g.student.entry.Student;
     9 import cn.yj3g.student.entry.TableContanst;
    10 
    11 public class ShowStudentActivity extends Activity {
    12 
    13     @Override
    14     public void onCreate(Bundle savedInstanceState) {
    15         super.onCreate(savedInstanceState);
    16         setContentView(R.layout.student_info);
    17         Intent intent = getIntent();
    18         Student student = (Student) intent.getSerializableExtra(TableContanst.STUDENT_TABLE);
    19         ((TextView)findViewById(R.id.tv_info_id)).setText(student.getId()+"");
    20         ((TextView)findViewById(R.id.tv_info_name)).setText(student.getName());
    21         ((TextView)findViewById(R.id.tv_info_age)).setText(student.getAge()+"");
    22         ((TextView)findViewById(R.id.tv_info_sex)).setText(student.getSex());
    23         ((TextView)findViewById(R.id.tv_info_likes)).setText(student.getLike());
    24         ((TextView)findViewById(R.id.tv_info_train_date)).setText(student.getTrainDate());
    25         ((TextView)findViewById(R.id.tv_info_phone)).setText(student.getPhoneNumber());
    26     }
    27     
    28     public void goBack(View view) {
    29         finish();
    30     }
    31 }
    复制代码

    界面效果如下:

    最最重要的环节来了,我们做这个系统主要是为了管理学员,所以增加和修改学员信息是必不可少的,因此需要一个Activity来专门提供添加和修改学员信息。在这里还有一件重要的事情要做,那就是要设计添加和修改学员的界面,在这里可用用相对布局做比较简单。我在这里创建了一个AddStudentActivity来添加和修改学员信息,下面附上相关代码:

    add_student.xml

    复制代码
      1 <?xml version="1.0" encoding="utf-8"?>
      2 
      3 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
      4     android:layout_width="fill_parent"  
      5     android:layout_height="fill_parent"  
      6     android:fillViewport="true"  
      7     android:scrollbarStyle="outsideInset" > 
      8 <RelativeLayout 
      9     android:orientation="vertical"
     10     android:layout_width="fill_parent"
     11     android:layout_height="fill_parent"
     12     android:padding="5dip"
     13     >
     14     
     15     <TextView android:id="@+id/tv_stu_text_id"
     16         android:layout_width="80dip"
     17         android:layout_height="40dip"
     18         android:gravity="center_vertical|right"
     19         android:layout_marginRight="5dip"
     20         android:layout_marginTop="5dip"
     21         android:layout_marginBottom="5dip"
     22         android:textSize="16sp"
     23         android:text="学员ID:"
     24     />
     25     
     26     <TextView android:id="@+id/tv_stu_id"
     27         android:layout_width="fill_parent"
     28         android:layout_height="40dip"
     29         android:text="未分配ID"
     30         android:layout_toRightOf="@id/tv_stu_text_id"
     31         android:layout_alignParentRight="true"
     32         android:layout_alignTop="@id/tv_stu_text_id"
     33         android:gravity="center"
     34         android:background="#ffffff"
     35         android:textColor="#000000"
     36         android:textSize="16sp"
     37     />
     38     
     39     <TextView android:id="@+id/tv_name_text"
     40         android:layout_width="80dip"
     41         android:layout_height="40dip"
     42         android:gravity="center_vertical|right"
     43         android:layout_marginRight="5dip"
     44         android:layout_below="@id/tv_stu_text_id"
     45         android:layout_alignLeft="@id/tv_stu_text_id"
     46         android:layout_marginBottom="5dip"
     47         android:textSize="16sp"
     48         android:text="姓名:"
     49     />
     50     
     51     <EditText android:id="@+id/et_name"
     52         android:layout_width="fill_parent"
     53         android:layout_height="40dip"
     54         android:layout_toRightOf="@id/tv_name_text"
     55         android:layout_alignParentRight="true"
     56         android:layout_alignTop="@id/tv_name_text"
     57         android:hint="请输入姓名"
     58         android:inputType="textPersonName"
     59         android:paddingLeft="20dip"/>
     60     
     61     <TextView android:id="@+id/tv_age_text"
     62         android:layout_width="80dip"
     63         android:layout_height="40dip"
     64         android:gravity="center_vertical|right"
     65         android:layout_marginRight="5dip"
     66         android:layout_below="@id/tv_name_text"
     67         android:layout_marginBottom="5dip"
     68         android:textSize="16sp"
     69         android:text="年龄:"
     70     />
     71     
     72     <EditText android:id="@+id/et_age"
     73         android:layout_width="fill_parent"
     74         android:layout_height="40dip"
     75         android:layout_toRightOf="@id/tv_age_text"
     76         android:layout_alignParentRight="true"
     77         android:layout_alignTop="@id/tv_age_text"
     78         android:hint="请输入年龄"
     79         android:paddingLeft="20dip"
     80         android:maxLength="3"
     81         android:inputType="number"
     82     />
     83     
     84     <TextView android:id="@+id/tv_sex_text"
     85         android:layout_width="80dip"
     86         android:layout_height="40dip"
     87         android:gravity="center_vertical|right"
     88         android:layout_below="@id/tv_age_text"
     89         android:layout_alignLeft="@id/tv_age_text"
     90         android:layout_marginRight="5dip"
     91         android:layout_marginBottom="5dip"
     92         android:text="性别:"
     93         android:textSize="16sp"
     94     />
     95     
     96     <RadioGroup
     97         android:id="@+id/rg_sex"
     98         android:layout_width="fill_parent"
     99         android:layout_height="40dip"
    100         android:orientation="horizontal"
    101         android:layout_toRightOf="@id/tv_sex_text"
    102         android:layout_alignParentRight="true"
    103         android:layout_alignTop="@id/tv_sex_text"
    104         >
    105         <RadioButton
    106           android:id="@+id/rb_sex_male"
    107           android:layout_width="wrap_content"
    108           android:layout_height="wrap_content"
    109           android:layout_weight="1"
    110           android:text=""
    111           android:textSize="16sp"
    112         />
    113         <RadioButton android:layout_width="wrap_content" 
    114         android:layout_height="wrap_content" 
    115         android:text="" 
    116         android:id="@+id/rb_sex_female"
    117         android:layout_weight="1"
    118         android:textSize="16sp">
    119         </RadioButton>
    120     </RadioGroup>
    121     
    122     <TextView  android:id="@+id/tv_likes_text"
    123         android:layout_width="80dip"
    124         android:layout_height="40dip"
    125         android:gravity="center_vertical|right"
    126         android:layout_below="@id/rg_sex"
    127         android:layout_alignLeft="@id/tv_sex_text"
    128         android:layout_marginRight="5dip"
    129         android:layout_marginBottom="5dip"
    130         android:text="爱好:"
    131         android:textSize="16sp"
    132     />
    133     <CheckBox
    134     android:id="@+id/box1"
    135             android:layout_width="wrap_content" android:layout_height="wrap_content"
    136             android:layout_toRightOf="@id/tv_likes_text"
    137             android:layout_below="@+id/rg_sex"
    138             android:layout_alignLeft="@+id/group1"
    139             android:text="@string/box1"
    140     ></CheckBox>
    141     <CheckBox
    142     android:id="@+id/box2"
    143             android:layout_width="wrap_content" android:layout_height="wrap_content"
    144             android:layout_toRightOf="@+id/box1"
    145             android:layout_below="@+id/rg_sex"
    146             android:layout_alignTop="@+id/box1"
    147             android:text="@string/box2"
    148     ></CheckBox>
    149     <CheckBox
    150     android:id="@+id/box3"
    151             android:layout_width="wrap_content" android:layout_height="wrap_content"
    152             android:layout_toRightOf="@+id/box2"
    153             android:layout_below="@+id/rg_sex"
    154             android:layout_alignTop="@+id/box2"
    155             android:text="@string/box3"
    156     ></CheckBox>
    157     
    158     <TextView android:id="@+id/tv_phone_text"
    159         android:layout_width="80dip"
    160         android:layout_height="40dip"
    161         android:gravity="center_vertical|right"
    162         android:layout_marginRight="5dip"
    163         android:layout_below="@id/tv_likes_text"
    164         android:layout_marginBottom="5dip"
    165         android:textSize="16sp"
    166         android:text="联系电话:"
    167     />
    168     
    169     <EditText android:id="@+id/et_phone"
    170         android:layout_width="fill_parent"
    171         android:layout_height="40dip"
    172         android:layout_toRightOf="@id/tv_phone_text"
    173         android:layout_alignParentRight="true"
    174         android:layout_alignTop="@id/tv_phone_text"
    175         android:hint="请输入手机号"
    176         android:paddingLeft="20dip"
    177         android:inputType="phone"
    178         android:maxLength="11"
    179     />
    180     
    181     <TextView android:id="@+id/tv_traindate_text"
    182         android:layout_width="80dip"
    183         android:layout_height="40dip"
    184         android:gravity="center_vertical|right"
    185         android:layout_marginRight="5dip"
    186         android:layout_below="@id/tv_phone_text"
    187         android:layout_marginBottom="5dip"
    188         android:textSize="16sp"
    189         android:text="入学日期"
    190         
    191     />
    192     
    193     <EditText android:id="@+id/et_traindate"
    194         android:layout_width="fill_parent"
    195         android:layout_height="40dip"
    196         android:layout_toRightOf="@id/tv_traindate_text"
    197         android:layout_alignParentRight="true"
    198         android:layout_alignTop="@id/tv_traindate_text"
    199         android:hint="点击选择日期"
    200         android:inputType="date"
    201         android:paddingLeft="20dip"
    202         android:focusable="false"
    203     />
    204     <Button android:id="@+id/btn_save" 
    205         android:layout_width="wrap_content" 
    206         android:layout_height="wrap_content" 
    207         android:text="保存" 
    208         android:layout_below="@id/tv_traindate_text" 
    209         android:layout_alignRight="@id/rg_sex">
    210     </Button>
    211     <Button android:id="@+id/btn_clear" 
    212         android:layout_width="wrap_content" 
    213         android:layout_height="wrap_content" 
    214         android:text="重置" 
    215         android:layout_below="@id/tv_traindate_text" 
    216         android:layout_toLeftOf="@id/btn_save"
    217         android:layout_marginRight="10dip">
    218     </Button>
    219 </RelativeLayout>
    220 </ScrollView>
    复制代码

    AddStudentActivity代码:

    复制代码
      1 package cn.yj3g.student.activity;
      2 
      3 import java.io.Serializable;
      4 import java.text.SimpleDateFormat;
      5 import java.util.Calendar;
      6 import java.util.Date;
      7 import java.util.HashSet;
      8 
      9 import android.app.Activity;
     10 import android.app.DatePickerDialog;
     11 import android.app.Dialog;
     12 import android.content.ContentValues;
     13 import android.content.Intent;
     14 import android.database.sqlite.SQLiteDatabase;
     15 import android.os.Bundle;
     16 import android.view.View;
     17 import android.view.View.OnClickListener;
     18 import android.widget.Button;
     19 import android.widget.CheckBox;
     20 import android.widget.CompoundButton;
     21 import android.widget.CompoundButton.OnCheckedChangeListener;
     22 import android.widget.DatePicker;
     23 import android.widget.EditText;
     24 import android.widget.RadioButton;
     25 import android.widget.RadioGroup;
     26 import android.widget.TextView;
     27 import android.widget.Toast;
     28 import cn.yj3g.student.dao.StudentDao;
     29 import cn.yj3g.student.db.StudentDBHelper;
     30 import cn.yj3g.student.entry.Student;
     31 import cn.yj3g.student.entry.TableContanst;
     32 
     33 public class AddStudentActivity extends Activity implements OnClickListener {
     34 
     35     private static final String TAG = "AddStudentActivity";
     36     private final static int DATE_DIALOG = 1;
     37     private static final int DATE_PICKER_ID = 1;
     38     private TextView idText;
     39     private EditText nameText;
     40     private EditText ageText;
     41     private EditText phoneText;
     42     private EditText dataText;
     43     private RadioGroup group;
     44     private RadioButton button1;
     45     private RadioButton button2;
     46     private CheckBox box1;
     47     private CheckBox box2;
     48     private CheckBox box3;
     49     private Button restoreButton;
     50     private String sex;
     51     private Button resetButton;
     52     private Long student_id;
     53 
     54     private StudentDao dao;
     55     private boolean isAdd = true;
     56 
     57     @Override
     58     public void onCreate(Bundle savedInstanceState) {
     59         super.onCreate(savedInstanceState);
     60         setContentView(R.layout.add_student);
     61         idText = (TextView) findViewById(R.id.tv_stu_id);
     62         nameText = (EditText) findViewById(R.id.et_name);
     63         ageText = (EditText) findViewById(R.id.et_age);
     64         button1 = (RadioButton) findViewById(R.id.rb_sex_female);
     65         button2 = (RadioButton) findViewById(R.id.rb_sex_male);
     66         phoneText = (EditText) findViewById(R.id.et_phone);
     67         dataText = (EditText) findViewById(R.id.et_traindate);
     68         group = (RadioGroup) findViewById(R.id.rg_sex);
     69         box1 = (CheckBox) findViewById(R.id.box1);
     70         box2 = (CheckBox) findViewById(R.id.box2);
     71         box3 = (CheckBox) findViewById(R.id.box3);
     72 
     73         restoreButton = (Button) findViewById(R.id.btn_save);
     74         resetButton = (Button) findViewById(R.id.btn_clear);
     75         dao = new StudentDao(new StudentDBHelper(this));
     76 
     77         // 设置监听
     78         restoreButton.setOnClickListener(this);
     79         resetButton.setOnClickListener(this);
     80         dataText.setOnClickListener(this);
     81         checkIsAddStudent();
     82     }
     83 
     84     /**
     85      * 检查此时Activity是否用于添加学员信息
     86      */
     87     private void checkIsAddStudent() {
     88         Intent intent = getIntent();
     89         Serializable serial = intent
     90                 .getSerializableExtra(TableContanst.STUDENT_TABLE);
     91         if (serial == null) {
     92             isAdd = true;
     93             dataText.setText(getCurrentDate());
     94         } else {
     95             isAdd = false;
     96             Student s = (Student) serial;
     97             showEditUI(s);
     98 
     99         }
    100     }
    101 
    102     /**
    103      * 显示学员信息更新的UI
    104      */
    105     private void showEditUI(Student student) {
    106         // 先将Student携带的数据还原到student的每一个属性中去
    107         student_id = student.getId();
    108         String name = student.getName();
    109         int age = student.getAge();
    110         String phone = student.getPhoneNumber();
    111         String data = student.getTrainDate();
    112         String like = student.getLike();
    113         String sex = student.getSex();
    114         if (sex.toString().equals("")) {
    115             button2.setChecked(true);
    116         } else if (sex.toString().equals("")) {
    117             button1.setChecked(true);
    118         }
    119         if (like != null && !"".equals(like)) {
    120             if (box1.getText().toString().indexOf(like) >= 0) {
    121                 box1.setChecked(true);
    122             }
    123             if (box2.getText().toString().indexOf(like) >= 0) {
    124                 box2.setChecked(true);
    125             }
    126             if (box3.getText().toString().indexOf(like) >= 0) {
    127                 box3.setChecked(true);
    128             }
    129         }
    130         // 还原数据
    131         idText.setText(student_id + "");
    132         nameText.setText(name + "");
    133         ageText.setText(age + "");
    134         phoneText.setText(phone + "");
    135         dataText.setText(data + "");
    136         setTitle("学员信息更新");
    137         restoreButton.setText("更新");
    138     }
    139 
    140     public void onClick(View v) {
    141         // 收集数据
    142         if (v == restoreButton) {
    143             if (!checkUIInput()) {// 界面输入验证
    144                 return;
    145             }
    146             Student student = getStudentFromUI();
    147             if (isAdd) {
    148                 long id = dao.addStudent(student);
    149                 dao.closeDB();
    150                 if (id > 0) {
    151                     Toast.makeText(this, "保存成功, ID=" + id, 0).show();
    152                     finish();
    153                 } else {
    154                     Toast.makeText(this, "保存失败,请重新输入!", 0).show();
    155                 }
    156             } else if (!isAdd) {
    157                 long id = dao.addStudent(student);
    158                 dao.closeDB();
    159                 if (id > 0) {
    160                     Toast.makeText(this, "更新成功", 0).show();
    161                     finish();
    162                 } else {
    163                     Toast.makeText(this, "更新失败,请重新输入!", 0).show();
    164                 }
    165             }
    166 
    167         } else if (v == resetButton) {
    168             clearUIData();
    169         } else if (v == dataText) {
    170             showDialog(DATE_PICKER_ID);
    171         }
    172     }
    173 
    174     /**
    175      * 清空界面的数据
    176      */
    177     private void clearUIData() {
    178         nameText.setText("");
    179         ageText.setText("");
    180         phoneText.setText("");
    181         dataText.setText("");
    182         box1.setChecked(false);
    183         box2.setChecked(false);
    184         group.clearCheck();
    185     }
    186 
    187     /**
    188      * 收集界面输入的数据,并将封装成Student对象
    189      */
    190     private Student getStudentFromUI() {
    191         String name = nameText.getText().toString();
    192         int age = Integer.parseInt(ageText.getText().toString());
    193         String sex = ((RadioButton) findViewById(group
    194                 .getCheckedRadioButtonId())).getText().toString();
    195         String likes = "";
    196         if (box1.isChecked()) { // basketball, football football
    197             likes += box1.getText();
    198         }
    199         if (box2.isChecked()) {
    200             if (likes.equals("")) {
    201                 likes += box2.getText();
    202             } else {
    203                 likes += "," + box2.getText();
    204             }
    205             if (likes.equals("")) {
    206                 likes += box3.getText();
    207             } else {
    208                 likes += "," + box3.getText();
    209             }
    210         }
    211         String trainDate = dataText.getText().toString();
    212         String phoneNumber = phoneText.getText().toString();
    213         String modifyDateTime = getCurrentDateTime();
    214         Student s=new Student(name, age, sex, likes, phoneNumber, trainDate,
    215                 modifyDateTime);
    216         if (!isAdd) {
    217             s.setId(Integer.parseInt(idText.getText().toString()));
    218             dao.deleteStudentById(student_id);
    219         }
    220         return s;
    221     }
    222 
    223     /**
    224      * 得到当前的日期时间
    225      */
    226     private String getCurrentDateTime() {
    227         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    228         return format.format(new Date());
    229     }
    230     /**
    231      * 得到当前的日期
    232      */
    233     private String getCurrentDate() {
    234         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    235         return format.format(new Date());
    236     }
    237     /**
    238      * 验证用户是否按要求输入了数据
    239      */
    240     private boolean checkUIInput() { // name, age, sex
    241         String name = nameText.getText().toString();
    242         String age = ageText.getText().toString();
    243         int id = group.getCheckedRadioButtonId();
    244         String message = null;
    245         View invadView = null;
    246         if (name.trim().length() == 0) {
    247             message = "请输入姓名!";
    248             invadView = nameText;
    249         } else if (age.trim().length() == 0) {
    250             message = "请输入年龄!";
    251             invadView = ageText;
    252         } else if (id == -1) {
    253             message = "请选择性别!";
    254         }
    255         if (message != null) {
    256             Toast.makeText(this, message, 0).show();
    257             if (invadView != null)
    258                 invadView.requestFocus();
    259             return false;
    260         }
    261         return true;
    262     }
    263 
    264     private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
    265         @Override
    266         public void onDateSet(DatePicker view, int year, int monthOfYear,
    267                 int dayOfMonth) {
    268             dataText.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
    269         }
    270     };
    271 
    272     @Override
    273     protected Dialog onCreateDialog(int id) {
    274         switch (id) {
    275         case DATE_PICKER_ID:
    276             return new DatePickerDialog(this, onDateSetListener, 2011, 8, 14);
    277         }
    278         return null;
    279     }
    280 }
    复制代码

    界面效果如下:

    修改界面:

    在这里我还做了一个额外的功能就是模糊查找,有想法的可以参考下。

    StudentSearch代码:

    复制代码
    package cn.yj3g.student.activity;
    
    import cn.yj3g.student.dao.StudentDao;
    import cn.yj3g.student.db.StudentDBHelper;
    import cn.yj3g.student.entry.TableContanst;
    import android.app.Activity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    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 StudentSearch extends Activity implements 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.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();
            }
        }
    }
    复制代码

    search.xml

    复制代码
     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:orientation="vertical"
     4     android:layout_width="fill_parent" 
     5     android:layout_height="fill_parent" >
     6     <EditText 
     7         android:id="@+id/et_srarch"
     8         android:layout_width="fill_parent" 
     9         android:layout_height="wrap_content"
    10         android:hint="请输入学员姓名"
    11         android:inputType="textPersonName"
    12     />
    13     <Button 
    14         android:id="@+id/bn_sure_search"
    15         android:gravity="center"
    16         android:layout_width="fill_parent" 
    17         android:layout_height="wrap_content"
    18         android:text="确定"
    19         />
    20         <Button 
    21         android:id="@+id/bn_return"
    22         android:gravity="center"
    23         android:layout_width="fill_parent" 
    24         android:layout_height="wrap_content"
    25         android:text="返回"
    26         />
    27         
    28 <LinearLayout android:id="@+id/linersearch"
    29                 android:orientation="vertical"
    30                 android:visibility="gone"
    31                 android:layout_width="fill_parent" 
    32                 android:layout_height="wrap_content">
    33     <ListView
    34     android:id="@+id/searchListView"
    35     android:layout_weight="1"
    36     android:layout_width="fill_parent"
    37     android:layout_height="wrap_content"/>
    38     <Button 
    39     android:id="@+id/return_id"
    40     android:layout_width="fill_parent"
    41     android:layout_height="wrap_content"
    42     android:text="返回"
    43     />                
    44 </LinearLayout>
    45 </LinearLayout>
    复制代码

    find_student_list_item.xml

    复制代码
     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:orientation="horizontal" android:layout_width="fill_parent"
     4     android:layout_height="wrap_content">
     5     <ImageView android:layout_width="fill_parent"
     6         android:layout_height="wrap_content" android:layout_weight="1"
     7         android:background="@drawable/icon" />
     8         <TextView android:id="@+id/tv_stu_id" android:layout_width="fill_parent"
     9         android:layout_height="wrap_content" android:layout_weight="1" />
    10     <TextView android:id="@+id/tv_stu_name" android:layout_width="fill_parent"
    11         android:layout_height="wrap_content" android:layout_weight="1" />
    12     <TextView android:id="@+id/tv_stu_age" android:layout_width="fill_parent"
    13         android:layout_height="wrap_content" android:layout_weight="1" />
    14     <TextView android:id="@+id/tv_stu_sex" android:layout_width="fill_parent"
    15         android:layout_height="wrap_content" android:layout_weight="1" />
    16     <TextView android:id="@+id/tv_stu_likes" android:layout_width="fill_parent"
    17         android:layout_height="wrap_content" android:layout_weight="1" />
    18     <TextView android:id="@+id/tv_stu_phone"
    19         android:layout_width="fill_parent" android:layout_height="wrap_content"
    20         android:layout_weight="1" />
    21     <TextView android:id="@+id/tv_stu_traindate" android:layout_width="fill_parent"
    22         android:layout_height="wrap_content" android:layout_weight="1" />
    23 
    24 </LinearLayout>
    复制代码

    界面效果如下:

    查询结果界面:

    在这里还牵扯到了一些常量和数据库的连接以及增删改查等操作,我用我们老师的方法将他们分别放在不同的包里。下面附上代码:

    StudentDao类

    复制代码
      1 package cn.yj3g.student.dao;
      2 
      3 import java.util.ArrayList;
      4 import java.util.HashMap;
      5 import java.util.List;
      6 import java.util.Map;
      7 import android.content.ContentValues;
      8 import android.database.Cursor;
      9 import android.database.sqlite.SQLiteDatabase;
     10 import android.view.View;
     11 import android.widget.SimpleCursorAdapter;
     12 import android.widget.TextView;
     13 import cn.yj3g.student.activity.R;
     14 import cn.yj3g.student.db.StudentDBHelper;
     15 import cn.yj3g.student.entry.Student;
     16 import cn.yj3g.student.entry.TableContanst;
     17 
     18 public class StudentDao {
     19 
     20     private StudentDBHelper dbHelper;
     21     private Cursor cursor;
     22     public StudentDao(StudentDBHelper dbHelper) {
     23         this.dbHelper = dbHelper;
     24     }
     25     // 添加一个Student对象数据到数据库表
     26     public long addStudent(Student s) {
     27 
     28         ContentValues values = new ContentValues();
     29         values.put(TableContanst.StudentColumns.NAME, s.getName());
     30         values.put(TableContanst.StudentColumns.AGE, s.getAge());
     31         values.put(TableContanst.StudentColumns.SEX, s.getSex());
     32         values.put(TableContanst.StudentColumns.LIKES, s.getLike());
     33         values.put(TableContanst.StudentColumns.PHONE_NUMBER, s.getPhoneNumber());
     34         values.put(TableContanst.StudentColumns.TRAIN_DATE, s.getTrainDate());
     35         values.put(TableContanst.StudentColumns.MODIFY_TIME, s.getModifyDateTime());
     36         return dbHelper.getWritableDatabase().insert(TableContanst.STUDENT_TABLE, null, values);
     37 
     38     }
     39 
     40     // 删除一个id所对应的数据库表student的记录
     41     public int deleteStudentById(long id) {
     42 
     43         return dbHelper.getWritableDatabase().delete(TableContanst.STUDENT_TABLE,
     44                 TableContanst.StudentColumns.ID + "=?", new String[] { id + "" });
     45     }
     46 
     47     // 更新一个id所对应数据库表student的记录
     48     public int updateStudent(Student s) {
     49 
     50         ContentValues values = new ContentValues();
     51         values.put(TableContanst.StudentColumns.NAME, s.getName());
     52         values.put(TableContanst.StudentColumns.AGE, s.getAge());
     53         values.put(TableContanst.StudentColumns.SEX, s.getSex());
     54         values.put(TableContanst.StudentColumns.LIKES, s.getLike());
     55         values.put(TableContanst.StudentColumns.PHONE_NUMBER, s.getPhoneNumber());
     56         values.put(TableContanst.StudentColumns.TRAIN_DATE, s.getTrainDate());
     57         values.put(TableContanst.StudentColumns.MODIFY_TIME, s.getModifyDateTime());
     58         return dbHelper.getWritableDatabase().update(TableContanst.STUDENT_TABLE, values,
     59                 TableContanst.StudentColumns.ID + "=?", new String[] { s.getId() + "" });
     60 
     61     }
     62 
     63     // 查询所有的记录
     64     public List<Map<String,Object>> getAllStudents() { //modify_time desc
     65         
     66         List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
     67         Cursor cursor = dbHelper.getWritableDatabase().query(TableContanst.STUDENT_TABLE, null, null, null,
     68                 null, null, TableContanst.StudentColumns.MODIFY_TIME+" desc");
     69         while(cursor.moveToNext()) {
     70             Map<String, Object> map = new HashMap<String, Object>(8);
     71             long id = cursor.getInt(cursor.getColumnIndex(TableContanst.StudentColumns.ID));
     72             map.put(TableContanst.StudentColumns.ID, id);
     73             String name = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.NAME));
     74             map.put(TableContanst.StudentColumns.NAME, name);
     75             int age = cursor.getInt(cursor.getColumnIndex(TableContanst.StudentColumns.AGE));
     76             map.put(TableContanst.StudentColumns.AGE, age);
     77             String sex = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.SEX));
     78             map.put(TableContanst.StudentColumns.SEX, sex);
     79             String likes = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.LIKES));
     80             map.put(TableContanst.StudentColumns.LIKES, likes);
     81             String phone_number = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.PHONE_NUMBER));
     82             map.put(TableContanst.StudentColumns.PHONE_NUMBER, phone_number);
     83             String train_date = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.TRAIN_DATE));
     84             map.put(TableContanst.StudentColumns.TRAIN_DATE, train_date);
     85             String modify_time = cursor.getString(cursor.getColumnIndex(TableContanst.StudentColumns.MODIFY_TIME));
     86             map.put(TableContanst.StudentColumns.MODIFY_TIME, modify_time);
     87             data.add(map);
     88         }
     89         return data;
     90     }
     91     //模糊查询一条记录
     92     public Cursor findStudent(String name){
     93     
     94         Cursor cursor = dbHelper.getWritableDatabase().query(TableContanst.STUDENT_TABLE,  null, "name like ?",
     95                 new String[] { "%" + name + "%" }, null, null, null,null);
     96     return cursor;
     97     }
     98     //按姓名进行排序
     99     public Cursor sortByName(){
    100         Cursor cursor = dbHelper.getWritableDatabase().query(TableContanst.STUDENT_TABLE,  null,null,
    101                 null, null, null,TableContanst.StudentColumns.NAME);
    102     return cursor;
    103     }
    104     //按入学日期进行排序
    105     public Cursor sortByTrainDate(){
    106         Cursor cursor = dbHelper.getWritableDatabase().query(TableContanst.STUDENT_TABLE,  null,null,
    107                 null, null, null,TableContanst.StudentColumns.TRAIN_DATE);
    108     return cursor;
    109     }
    110     //按学号进行排序
    111     public Cursor sortByID(){
    112         Cursor cursor = dbHelper.getWritableDatabase().query(TableContanst.STUDENT_TABLE,  null,null,
    113                 null, null, null,TableContanst.StudentColumns.ID);
    114     return cursor;
    115     }
    116     public void closeDB() {
    117         dbHelper.close();
    118     }
    119     //自定义的方法通过View和Id得到一个student对象
    120     public Student getStudentFromView(View view, long id) {
    121         TextView nameView = (TextView) view.findViewById(R.id.tv_stu_name);
    122         TextView ageView = (TextView) view.findViewById(R.id.tv_stu_age);
    123         TextView sexView = (TextView) view.findViewById(R.id.tv_stu_sex);
    124         TextView likeView = (TextView) view.findViewById(R.id.tv_stu_likes);
    125         TextView phoneView = (TextView) view.findViewById(R.id.tv_stu_phone);
    126         TextView dataView = (TextView) view.findViewById(R.id.tv_stu_traindate);
    127         String name = nameView.getText().toString();
    128         int age = Integer.parseInt(ageView.getText().toString());
    129         String sex = sexView.getText().toString();
    130         String like = likeView.getText().toString();
    131         String phone = phoneView.getText().toString();
    132         String data = dataView.getText().toString();
    133         Student student = new Student(id, name, age, sex, like, phone, data,null);
    134         return student;
    135     }
    136     
    137 }
    复制代码

    StudentDBHelper类

    复制代码
     1 package cn.yj3g.student.db;
     2 
     3 import cn.yj3g.student.entry.TableContanst;
     4 import android.content.Context;
     5 import android.database.sqlite.SQLiteDatabase;
     6 import android.database.sqlite.SQLiteDatabase.CursorFactory;
     7 import android.database.sqlite.SQLiteOpenHelper;
     8 import android.util.Log;
     9 
    10 public class StudentDBHelper extends SQLiteOpenHelper {
    11 
    12     private static final String TAG = "StudentDBHelper";
    13 
    14     public static final String DB_NAME = "student_manager.db";
    15     public static final int VERSION = 1;
    16     //构造方法
    17     public StudentDBHelper(Context context, String name, CursorFactory factory, int version) {
    18         super(context, name, factory, version);
    19 
    20     }
    21 
    22     public StudentDBHelper(Context context) {
    23         this(context, DB_NAME, null, VERSION);
    24     }
    25     //创建数据库
    26     @Override
    27     public void onCreate(SQLiteDatabase db) {
    28         Log.v(TAG, "onCreate");
    29         db.execSQL("create table "
    30                 + TableContanst.STUDENT_TABLE
    31                 + "(_id Integer primary key AUTOINCREMENT,"
    32                 + "name char,age integer, sex char, likes char, phone_number char,train_date date, "
    33                 + "modify_time DATETIME)");
    34     }
    35     //更新数据库
    36     @Override
    37     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    38         Log.v(TAG, "onUpgrade");
    39     }
    40 
    41 }
    复制代码

    Student类:

    复制代码
      1 package cn.yj3g.student.entry;
      2 
      3 import java.io.Serializable;
      4 
      5 import android.view.View;
      6 import android.widget.TextView;
      7 import cn.yj3g.student.activity.R;
      8 
      9 public class Student implements Serializable{
     10 
     11     private long id;
     12     private String name;
     13     private int age;
     14     private String sex;
     15     private String like;
     16     private String phoneNumber;
     17     private String trainDate;
     18     private String modifyDateTime;
     19     
     20     
     21     public Student() {
     22         super();
     23     }
     24 
     25     public Student(long id, String name, int age, String sex, String like, String phoneNumber,
     26             String trainDate, String modifyDateTime) {
     27         super();
     28         this.id = id;
     29         this.name = name;
     30         this.age = age;
     31         this.sex = sex;
     32         this.like = like;
     33         this.phoneNumber = phoneNumber;
     34         this.trainDate = trainDate;
     35         this.modifyDateTime = modifyDateTime;
     36     }
     37     
     38     public Student(String name, int age, String sex, String like, String phoneNumber,
     39             String trainDate, String modifyDateTime) {
     40         super();
     41         this.name = name;
     42         this.age = age;
     43         this.sex = sex;
     44         this.like = like;
     45         this.phoneNumber = phoneNumber;
     46         this.trainDate = trainDate;
     47         this.modifyDateTime = modifyDateTime;
     48     }
     49 
     50     public long getId() {
     51         return id;
     52     }
     53     public void setId(long id) {
     54         this.id = id;
     55     }
     56     public String getName() {
     57         return name;
     58     }
     59     public void setName(String name) {
     60         this.name = name;
     61     }
     62     public int getAge() {
     63         return age;
     64     }
     65     public void setAge(int age) {
     66         this.age = age;
     67     }
     68     public String getSex() {
     69         return sex;
     70     }
     71     public void setSex(String sex) {
     72         this.sex = sex;
     73     }
     74     public String getLike() {
     75         return like;
     76     }
     77     public void setLike(String like) {
     78         this.like = like;
     79     }
     80     public String getPhoneNumber() {
     81         return phoneNumber;
     82     }
     83     public void setPhoneNumber(String phoneNumber) {
     84         this.phoneNumber = phoneNumber;
     85     }
     86     public String getTrainDate() {
     87         return trainDate;
     88     }
     89     public void setTrainDate(String trainDate) {
     90         this.trainDate = trainDate;
     91     }
     92     public String getModifyDateTime() {
     93         return modifyDateTime;
     94     }
     95     public void setModifyDateTime(String modifyDateTime) {
     96         this.modifyDateTime = modifyDateTime;
     97     }
     98     @Override
     99     public int hashCode() {
    100         final int prime = 31;
    101         int result = 1;
    102         result = prime * result + age;
    103         result = prime * result + (int) (id ^ (id >>> 32));
    104         result = prime * result + ((like == null) ? 0 : like.hashCode());
    105         result = prime * result + ((modifyDateTime == null) ? 0 : modifyDateTime.hashCode());
    106         result = prime * result + ((name == null) ? 0 : name.hashCode());
    107         result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode());
    108         result = prime * result + ((sex == null) ? 0 : sex.hashCode());
    109         result = prime * result + ((trainDate == null) ? 0 : trainDate.hashCode());
    110         return result;
    111     }
    112     @Override
    113     public boolean equals(Object obj) {
    114         if (this == obj)
    115             return true;
    116         if (obj == null)
    117             return false;
    118         if (getClass() != obj.getClass())
    119             return false;
    120         Student other = (Student) obj;
    121         if (age != other.age)
    122             return false;
    123         if (id != other.id)
    124             return false;
    125         if (like == null) {
    126             if (other.like != null)
    127                 return false;
    128         } else if (!like.equals(other.like))
    129             return false;
    130         if (modifyDateTime == null) {
    131             if (other.modifyDateTime != null)
    132                 return false;
    133         } else if (!modifyDateTime.equals(other.modifyDateTime))
    134             return false;
    135         if (name == null) {
    136             if (other.name != null)
    137                 return false;
    138         } else if (!name.equals(other.name))
    139             return false;
    140         if (phoneNumber == null) {
    141             if (other.phoneNumber != null)
    142                 return false;
    143         } else if (!phoneNumber.equals(other.phoneNumber))
    144             return false;
    145         if (sex == null) {
    146             if (other.sex != null)
    147                 return false;
    148         } else if (!sex.equals(other.sex))
    149             return false;
    150         if (trainDate == null) {
    151             if (other.trainDate != null)
    152                 return false;
    153         } else if (!trainDate.equals(other.trainDate))
    154             return false;
    155         return true;
    156     }
    157     @Override
    158     public String toString() {
    159         return "Student [id=" + id + ", name=" + name + "]";
    160     }
    161 }
    复制代码

    常量TableContanst类:

    复制代码
     1 package cn.yj3g.student.entry;
     2 
     3 public final class TableContanst {
     4     
     5     public static final String STUDENT_TABLE = "student";
     6     
     7     public static final class StudentColumns {
     8         public static final String ID = "_id";
     9         public static final String NAME = "name";
    10         public static final String AGE = "age";
    11         public static final String SEX = "sex";
    12         public static final String LIKES = "likes";
    13         public static final String PHONE_NUMBER = "phone_number";
    14         public static final String TRAIN_DATE = "train_date";
    15         public static final String MODIFY_TIME = "modify_time";
    16     }
    17 }
    复制代码

    最后我将我的values里的strings.xml和AndroidManifest.xml附在下面,以供大家参考。

    strings.xml:

    复制代码
     1 <?xml version="1.0" encoding="utf-8"?>
     2 <resources>
     3     <string name="hello">Hello World, TextStudentManager!</string>
     4     <string name="app_name">学员管理系统</string>
     5     <string name="information_write">学员信息修改</string>
     6     <string name="button1"></string>
     7     <string name="button2"></string>
     8     <string name="box1">唱歌</string>
     9     <string name="box2">跳舞</string>
    10     <string name="box3">健身</string>
    11     <string name="myButton">添加学员信息</string>
    12     <string name="spinner">请选择</string>    
    13 </resources>
    复制代码

    AndroidManifest.xml:

    复制代码
     1 <?xml version="1.0" encoding="utf-8"?>
     2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     3       package="cn.yj3g.student.activity"
     4       android:versionCode="1"
     5       android:versionName="1.0">
     6     <uses-sdk android:minSdkVersion="8" />
     7 
     8     <application android:icon="@drawable/student"  android:label="@string/app_name">
     9         <activity android:name=".StudentListActivity"
    10                   android:label="学员信息列表">
    11             <intent-filter>
    12                 <action android:name="android.intent.action.MAIN" />
    13                 <category android:name="android.intent.category.LAUNCHER" />
    14             </intent-filter>
    15         </activity>
    16         
    17          <activity android:name=".AddStudentActivity"
    18                   android:label="学员信息添加">
    19         </activity>
    20           <activity android:name=".ShowStudentActivity"
    21                   android:label="学员详细信息">
    22         </activity>
    23          <activity android:name=".StudentSearch"
    24                   android:label="学员信息查询">
    25         </activity>
    26          <activity android:name=".SearchResult"
    27                   android:label="查询结果">
    28         </activity>
    29         <provider 
    30         android:name=".MyStudentManagerProvider"
    31         android:authorities="cn.yj3g.student.activity.MyStudentManagerProvider"></provider>
    32         <uses-library android:name="android.test.runner" />  <!-- android测试包 -->
    33         
    34     </application>
    35     <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission> 
    36     <instrumentation android:name="android.test.InstrumentationTestRunner"
    37           android:targetPackage="cn.yj3g.student.activity" android:label="Tests for My App" />
    38 </manifest>
    复制代码


    由于自己也是初学者,所以大家发现什么问题,可以留言,大家一起学习。

    展开全文
  • 管理员:注册,登录管理系统,查询学生信息,添加学生信息,查看成绩排名,修改学生信息,删除学生信息,强制下线 学生:登录,查看个人详细信息,修改密码 以上功能用数据库实现 UI部分没做太多的修饰,主要用...

    项目部分截图:

     

     

     

    主要功能:

    管理员:注册,登录管理系统,查询学生信息,添加学生信息,查看成绩排名,修改学生信息,删除学生信息,强制下线

    学生:登录,查看个人详细信息,修改密码

    以上功能用数据库实现

     

    UI部分没做太多的修饰,主要用了圆形头像,自定义圆角button按钮,自定义Alertdialog布局然后就是相对布局和线性布局,圆形头像参考地址:http://blog.csdn.net/android_dong/article/details/41989499,自定义圆角button按钮参考地址:http://blog.csdn.net/jdsjlzx/article/details/42744095

    功能实现部分主要使用SQLite,对数据库进行增删改查,由于之前设计表的时候忘了一列所以使用数据库升级进行插入新列(表中的数据添加了很多不想卸了重建),使用正则限制密码是6个纯数字和性别的填写,使用了单例设计模式全局使用一个dbHelper,使用listView显示学生信息(支持listView点击触发事件),自定义listView布局,使用广播实现强制下线的功能

    项目的说明:的写这个项目没遇到太大的坑,不过有几点要注意,1、listView的每一行如果超出了屏幕会报错。2、两个Activity通过Intent启动同一个Activity,如果一个传数据一个不传数据会出错,应该通过传递一个boolean值进行控制,别的好像没遇到问题,在注册时要输入一个注册码,默认为10086,由于listView布局时要通过性别信息显示不同的图片,因此必填项(已做限制)否则出错,添加学生信息的界面在不同的手机上会出现不同的布局,我是按我手机的布局写的别的手机可能会出现不对称的情况,学生的总成绩排名是利用数据库的order by实现的,因此,要进行排名要先点    查看总成绩排名   这个按钮

     

    源码地址:点击打开链接

     

     

     

     

    展开全文
  • Android实现学生信息管理系统之登录与数据库准备 效果图 依赖 大部分组件来自于Design库 在build.gradle 文件中添加这样的代码 dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) ...

    前言

    数据库设计参考我的上一篇博客
    Android实现学生信息管理系统之登录与数据库准备
    代码我已经放到了github上,需要的可以下载
    https://github.com/SunnyBoy-WYH/AndroidDemo
    考虑到大家可能github下载慢,我也在码云放了一份
    https://gitee.com/SunnyBoy-WYH/AndroidDemo

    觉得还可以的可以Star一下…

    效果图

    在这里插入图片描述

    依赖

    大部分组件来自于Design库
    在build.gradle 文件中添加这样的代码

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:design:28.0.0'
    }
    

    要想使用circleimageview–圆形imageview也就是我的头像,只需要在上面依赖中添加如下一句

    implementation 'de.hdodenhof:circleimageview:2.1.0'
    

    添加依赖之后记得Sync now 编译一下 以让它下载你的依赖。

    侧滑菜单参考我之前的一篇博客
    Android 界面美化之DrawerLayout(抽屉式布局)+菜单栏导航实现

    XML布局代码

    用于提交留言的布局 activity_submit_message.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@mipmap/liuyan_new"
        tools:context=".student.submit_message">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:gravity="center"
            android:textSize="30dp"
            android:text="留言"/>
        <EditText android:text=""
            android:layout_marginTop="50dp"
            android:id="@+id/et_message"
    
            android:lines="5"
    
            android:gravity="top"
    
            android:hint="请输入您的反馈意见(字数500以内)!"
            android:textSize="20sp"
            android:textColor="#000000"
    
            android:layout_width="fill_parent"
    
            android:layout_height="wrap_content">
    
        </EditText>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="50dp"
            android:text="提交"
            android:background="@mipmap/color"
            android:id="@+id/button_submit"
            />
    
    </LinearLayout>
    

    选课界面的布局文件 activity_choose_course.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".student.choose_course"
        android:background="@mipmap/choosecourse"
        android:orientation="vertical">
        <ListView
            android:layout_width="match_parent"
            android:layout_height="650dp"
            android:layout_weight="9"
            android:id="@+id/listview_course">
    
        </ListView>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal">
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="选择"
                android:id="@+id/choose"
                android:layout_marginLeft="120dp"
                />
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/back"
                android:text="返回"/>
        </LinearLayout>
    
    
    </LinearLayout>
    

    java逻辑代码

    学生端主界面 activity_student.java

    package com.example.database_manage.student;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.NavigationView;
    import android.support.v4.content.FileProvider;
    import android.support.v4.view.GravityCompat;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;
    import android.widget.Toast;
    import com.example.database_manage.Common.Common_methon;
    import com.example.database_manage.Common.Common_toolbarColor;
    import com.example.database_manage.R;
    import com.example.database_manage.database.CommonDatabase;
    import com.example.database_manage.database.image_store;
    import com.example.database_manage.start_load.load;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    
    import de.hdodenhof.circleimageview.CircleImageView;
    
    public class activity_student extends AppCompatActivity  {
        private SQLiteDatabase db;
    
        //切换用户弹出的对话框
        private AlertDialog.Builder builder;
    
        //Toolbar用于替代原有的actionBar
        private Toolbar toolbar ;
    
        //用于显示学生选课信息的listview
        private ListView listView_mycourse;
    
        //侧滑
        private DrawerLayout drawerLayout;
        private NavigationView navigationView;
    
        //用于获取NavigationView的headlayout,方便监听子项
        private View headview;
    
        //headlayout中的textview
        private TextView textView_welcome;
    
        //headlayout中circleimage
        private CircleImageView circleImageView;
    
    
        private Uri imageUri;
    
        private static final int TAKE_PHOTO =1;
    
        private image_store imageStore;
    
        private  Intent intent_1;
    
        //悬浮按钮也就是加号,用于选课
        private FloatingActionButton floatingActionButton;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_student);
    
            initView();
    
            //获取登录信息,以锁定用户
            intent_1 = getIntent();
    
            final ActionBar actionBar = getSupportActionBar();
            if(actionBar!=null)
            {
                actionBar.setDisplayHomeAsUpEnabled(true);
    
                //设置左箭头图片
                actionBar.setHomeAsUpIndicator(R.drawable.a);
    
            }
    
            //headlayout中的欢迎实现
            textView_welcome.setText(findNameById(intent_1.getStringExtra("student_id")));
    
    
    
    
            //菜单栏实现
            navigationView.setCheckedItem(R.id.nav_menu_myinfo);
            navigationView.setCheckedItem(R.id.nav_menu_changeacc);
    
    
            //设置标题栏与状态栏颜色保持一致
            new Common_toolbarColor().toolbarColorSet(activity_student.this);
    
            //头像初始化
            Bitmap bitmap_temp = imageStore.getBmp(db,intent_1.getStringExtra("student_id"));
    
            if(bitmap_temp!=null)
            {
                circleImageView.setImageBitmap(bitmap_temp);
            }
    
    
            //NavigationView的菜单项监听器
            navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                    switch (menuItem.getItemId())
                    {
                        case R.id.nav_menu_myinfo:
                            Intent intent_about = new Intent(activity_student.this, about_me.class);
                            intent_about.putExtra("student_id", intent_1.getStringExtra("student_id"));
                            startActivity(intent_about);
    
                            break;
                        case R.id.nav_menu_changeacc:
                            builder = new AlertDialog.Builder(activity_student.this);
    
                            builder.setIcon(R.drawable.ic_launcher_background);
                            //    设置Title的内容
                            builder.setTitle("提示");
                            //    设置Content来显示一个信息
                            builder.setMessage("您确定要切换账号吗?");
                            //    设置一个PositiveButton
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    startActivity(new Intent(activity_student.this, load.class));
                                    finish();
                                }
                            });
                            //    设置一个NegativeButton
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    //取消就什么都不做
                                }
                            });
    
                            //  显示出该对话框
                            builder.show();
                            break;
                            //留言
                        case R.id.nav_menu_liuyan:
                            Intent intent_submit = new Intent(activity_student.this, submit_message.class);
                            intent_submit.putExtra("student_id", intent_1.getStringExtra("student_id"));
                            startActivity(intent_submit);
                            break;
    
                            //查看选课结果
                        case R.id.nav_menu_look_hcourse:
    
                        //两表连接查询
                        Cursor cursor = db.rawQuery(
                                "select * from student_course inner join course " +
                                        "on student_course.course_name =course.course_name " +
                                        "AND student_course.teacher_name = course.teacher_name  " +
                                        "where student_id = ?", new String[]{intent_1.getStringExtra("student_id")});
                        ArrayList<Map<String, String>> arrayList_1 = new ArrayList<Map<String, String>>();
                        if (cursor.getCount() == 0) {
                            Toast.makeText(activity_student.this, "您还没有选择任何课!", Toast.LENGTH_SHORT).show();
                        } else {
                            while (cursor.moveToNext()) {
                                Map<String, String> map = new HashMap<String, String>();
    
                                map.put("course_time", cursor.getString(cursor.getColumnIndex("course_time")));
                                map.put("course_name", cursor.getString(cursor.getColumnIndex("course_name")));
                                map.put("teacher_name", cursor.getString(cursor.getColumnIndex("teacher_name")));
                                map.put("course_period", cursor.getString(cursor.getColumnIndex("course_period")));
                                map.put("course_weight", cursor.getString(cursor.getColumnIndex("course_weight")));
                                arrayList_1.add(map);
    
                            }
                            //设置适配器,并绑定布局文件
                            SimpleAdapter simpleAdapter = new SimpleAdapter(activity_student.this, arrayList_1, R.layout.choose_result,
                                    new String[]{"course_name", "teacher_name", "course_time", "course_weight", "course_period"}, new int[]{R.id.result_course_name, R.id.result_teacher_name, R.id.result_time, R.id.result_weight, R.id.result_period});
                            listView_mycourse.setAdapter(simpleAdapter);
                        }
    
                        break;
    
                        default:
                            break;
                    }
                    return true;
                }
            });
    
    
    
            //为listview设定监听器
            View.OnClickListener listener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.floatingbutton_choose_course:
                            //再将从登陆界面接受的学生学号传给选择课程的活动
                            Intent intent_2 = new Intent(activity_student.this, choose_course.class);
                            intent_2.putExtra("student_id", intent_1.getStringExtra("student_id"));
                            startActivity(intent_2);
                            break;
                        case R.id.circleimage:
                            // 创建File对象,用于存储拍照后的图片
                            File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
                            try {
                                if (outputImage.exists()) {
                                    outputImage.delete();
                                }
                                outputImage.createNewFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            if (Build.VERSION.SDK_INT < 24) {
                                imageUri = Uri.fromFile(outputImage);
                            } else {
                                imageUri = FileProvider.getUriForFile(activity_student.this, "com.example.database_manage.fileprovider", outputImage);
                            }
                            // 启动相机程序
                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                            startActivityForResult(intent, TAKE_PHOTO);
    
                            break;
                        default:
                            break;
                    }
                }
            };
    
    
            floatingActionButton.setOnClickListener(listener);
            circleImageView.setOnClickListener(listener);
    
    
        }
    
        //点击头像拍照实现
        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            switch (requestCode)
            {
                case TAKE_PHOTO:
                    if(resultCode ==RESULT_OK)
                    {
                        try{
                            //将拍摄的照片显示到头像中
                            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                            circleImageView.setImageBitmap(bitmap);
    
                            //更新本人资源表
                            Bitmap bitmap1 = new Common_methon().compressBoundsBitmap(activity_student.this,imageUri,200,200);
                            imageStore.update(bitmap1,db,intent_1.getStringExtra("student_id"));
                        }catch (FileNotFoundException e)
                        {
                            e.printStackTrace();
    
                        }
    
                    }
                    break;
                default:
                    break;
            }
        }
    
        private void initView() {
    
            //获取数据库对象
            db = new CommonDatabase().getSqliteObject(activity_student.this, "test_db");
    
            listView_mycourse = findViewById(R.id.listview_mycourse);
    
            toolbar =findViewById(R.id.toolbar_student);
    
            setSupportActionBar(toolbar);
    
            drawerLayout = findViewById(R.id.drawerlayout_student);
    
            navigationView = findViewById(R.id.navigation_view);
    
            headview = navigationView.inflateHeaderView(R.layout.headlayout);
    
    
            textView_welcome = headview.findViewById(R.id.welcome_textview);
    
    
            circleImageView = headview.findViewById(R.id.circleimage);
    
            floatingActionButton = findViewById(R.id.floatingbutton_choose_course);
    
            imageStore = new image_store();
    
        }
    
        //
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
    
            switch (item.getItemId())
            {
                case android.R.id.home:
                    drawerLayout.openDrawer(GravityCompat.START);
    
                    break;
                default:
                    break;
            }
            return true;
        }
    
        //根据用户的学号去查找姓名
        public String findNameById(String id)
        {
            Cursor cursor = db.query("student",null,"id = ?",new String[]{id},null,null,null,null);
    
            //如果没查到
            if(cursor.getCount()==0)
            {
                return "无法获取您的个人信息";
            }
            else
            {
                String str = "";
                while(cursor.moveToNext())
                {
                    str = cursor.getString(cursor.getColumnIndex("name"));
                }
                return  str+" 欢迎您!";
            }
    
        }
    
    }
    
    

    我的信息界面 about_me.java

    package com.example.database_manage.student;
    
    import android.content.Intent;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.example.database_manage.R;
    import com.example.database_manage.database.CommonDatabase;
    /*
        我的信息功能实现,主要根据登录时传过来的intent所携带的数据
     */
    public class about_me extends AppCompatActivity {
        SQLiteDatabase db ;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_about_me);
    
            //获取数据库对象
            db = new CommonDatabase().getSqliteObject(about_me.this,"test_db");
    
            //获取登录时传来的信息
            final Intent intent_about_me =getIntent();
    
            //绑定组件
            TextView t_about_id = findViewById(R.id.aboutme_id);
            TextView t_about_name = findViewById(R.id.aboutme_name);
            TextView t_about_phone = findViewById(R.id.aboutme_phone);
            TextView t_about_banji = findViewById(R.id.aboutme_banji);
            TextView t_about_sex = findViewById(R.id.aboutme_sex);
            TextView t_about_age = findViewById(R.id.aboutme_age);
            TextView t_about_college = findViewById(R.id.aboutme_college);
    
            Cursor cursor_about = db.query("student",null,"id = ?",new String[]{intent_about_me.getStringExtra("student_id")},null,null,null);
            while(cursor_about.moveToNext())
            {
                //将通过id查询到的学生信息显示到界面中
                t_about_id.setText(cursor_about.getString(cursor_about.getColumnIndex("id")));
                t_about_name.setText(cursor_about.getString(cursor_about.getColumnIndex("name")));
                t_about_banji.setText(cursor_about.getString(cursor_about.getColumnIndex("banji")));
                t_about_phone.setText(cursor_about.getString(cursor_about.getColumnIndex("phone")));
                t_about_sex.setText(cursor_about.getString(cursor_about.getColumnIndex("sex")));
                t_about_age.setText(cursor_about.getString(cursor_about.getColumnIndex("age")));
                t_about_college.setText(cursor_about.getString(cursor_about.getColumnIndex("college")));
    
            }
            Button button_back = findViewById(R.id.button_finish_about);
            Button button_jidian = findViewById(R.id.button_query_jidian);
            button_jidian.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                //主要用于查询绩点
                    Cursor cursor1 =db.rawQuery(
                            "select * from student_course inner join course " +
                                    "on student_course.course_name =course.course_name " +
                                    "AND student_course.teacher_name = course.teacher_name  " +
                                    "where student_id = ?",new String[]{intent_about_me.getStringExtra("student_id")});
    
                    //设定比对数组,根据河北大学绩点对照
                    double[] duizhao = new double[105];
                    double fenmu =0.0;
                    double fenzi =0.0;
                    double temp=0.8;
    
                    for(int i=0;i<60;i++)
                    {
                        duizhao[i]=0;
                    }
    
                    for(int j=60;j<66;j++)
                    {
                        temp+=0.2;
                        duizhao[j]=temp;
    
    
                    }
                    temp=2.0;
                    for(int z=66;z<95;z++)
                    {
                        temp+=0.1;
                        duizhao[z]=temp;
                    }
                    for(int k=95;k<=100;k++)
                    {
                        duizhao[k]=5.0;
                    }
    
                    while(cursor1.moveToNext())
                    {
                        if(cursor1.getString(cursor1.getColumnIndex("score"))!=null) {
                            fenmu = fenmu + Double.parseDouble(cursor1.getString(cursor1.getColumnIndex("course_weight")));
                            fenzi += duizhao[Integer.parseInt(cursor1.getString(cursor1.getColumnIndex("score")))] * Double.parseDouble(cursor1.getString(cursor1.getColumnIndex("course_weight")));
                        }
    
                    }
                    if(fenmu<0.1)
                    {
                        Toast.makeText(about_me.this,"您还没有选任何课或您的成绩老师还没有注入哦",Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        Toast.makeText(about_me.this,"您的绩点为:"+String.valueOf(fenzi/fenmu),Toast.LENGTH_LONG).show();
                    }
    
    
    
                }
            });
    
    
            button_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }
    
    

    配合listview的选课自定义Adapter courseAdapter.java

    package com.example.database_manage.student;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.TextView;
    
    
    import com.example.database_manage.R;
    
    import java.util.List;
    
    /*
    主要用于设定listview的适配器
     */
    public class courseAdapter extends BaseAdapter {
         Context mContext;
         List<item> mList;
         ViewHolder mViewHolder;
    
        public  courseAdapter(Context mContext, List<item> mList)
        {
            this.mContext = mContext;
            this.mList = mList;
        }
        @Override
        public int getCount()
        {
            return mList.size();
        }
        @Override
        public Object getItem(int i)
        {
            return mList.get(i);
        }
        @Override
        public long getItemId(int i)
        {
            return i;
        }
        @Override
        public View getView(final int i, View view, ViewGroup viewGroup)
        {
            final item it = mList.get(i);
            if(view == null)
            {
                //用LayouInflater加载布局,传给布局对象view
                // 用view找到三个控件,存放在viewHolder中,再把viewHolder储存到View中
                // 完成了把控件展示在ListView的步骤
                 view = LayoutInflater.from(mContext).inflate(R.layout.list_item_course, viewGroup, false);
    
                 mViewHolder = new ViewHolder();
                 mViewHolder.checkBox = (CheckBox)view.findViewById(R.id.checkbox_1);
                 mViewHolder.course_name = (TextView)view.findViewById(R.id.t_course_name);
                 mViewHolder.course_time = (TextView)view.findViewById(R.id.t_course_time);
                 mViewHolder.course_period =(TextView) view.findViewById(R.id.t_course_period);
                 mViewHolder.teacher_name = view.findViewById(R.id.t_teacher_name);
                 mViewHolder.course_weight = view.findViewById(R.id.t_course_weight);
                 view.setTag(mViewHolder);
            }
            else
                {
    
                    mViewHolder = (ViewHolder) view.getTag();
                }
            mViewHolder.checkBox.setOnCheckedChangeListener (
                    new CompoundButton.OnCheckedChangeListener()
            {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b)
            {
                it.setIscheck(b);
            }
    
            });
            mViewHolder.course_name.setText(it.getCourse_name());
            mViewHolder.course_time.setText(it.getCourse_time());
            mViewHolder.course_period.setText(it.getCourse_period());
            mViewHolder.teacher_name.setText(it.getTeacher_name());
            mViewHolder.checkBox.setChecked(it.getIscheck());
            mViewHolder.course_weight.setText(it.getCourse_weight());
            return view;
            }
        class ViewHolder
        {
            TextView course_name;
            TextView course_time;
            CheckBox checkBox;
            TextView course_period;
            TextView teacher_name;
            TextView course_weight;
        }
    }
    
    

    配合自定义Adapter使用的子项类item, item.java

    package com.example.database_manage.student;
    /*
    item主要设计选课时的选中状态以及信息
     */
    public class item {
        String course_name;
        String course_time;
        String course_period;
        String course_weight;
        String teacher_name;
        Boolean ischeck;
    
    
        public  item(String course_name, String course_time, String course_period,String teacher_name,String course_weight)
        {
            this.course_name = course_name;
            this.course_time = course_time;
            this.course_period = course_period;
            this.teacher_name = teacher_name;
            this.course_weight = course_weight;
            this.ischeck = false;
    
        }
        public String getCourse_weight() {
            return course_weight;
        }
    
        public String getTeacher_name() {
            return teacher_name;
        }
    
        public void setTeacher_name(String teacher_name) {
            this.teacher_name = teacher_name;
        }
        public String getCourse_name() {
            return course_name;
        }
    
        public String getCourse_time() {
            return course_time;
        }
    
        public String getCourse_period() {
            return course_period;
        }
    
        public void setCourse_name(String course_name) {
            this.course_name = course_name;
        }
    
        public Boolean getIscheck() {
            return ischeck;
        }
    
        public void setIscheck(Boolean ischeck) {
            this.ischeck = ischeck;
        }
    }
    
    

    提交留言用的界面 submit_message.java

    package com.example.database_manage.student;
    
    import android.content.ContentValues;
    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.Toast;
    
    import com.example.database_manage.R;
    import com.example.database_manage.database.CommonDatabase;
    
    public class submit_message extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_submit_message);
            final EditText editText = findViewById(R.id.et_message);
            Button button_submit = findViewById(R.id.button_submit);
    
    
    
            button_submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(editText.getText().toString().equals(""))
                    {
                        Toast.makeText(submit_message.this,"留言不可以为空",Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put("student_id",getIntent().getStringExtra("student_id"));
                        contentValues.put("message",editText.getText().toString());
    
                        new CommonDatabase().getSqliteObject(submit_message.this,"test_db").
                                insert("message",null,contentValues);
                        Toast.makeText(submit_message.this,"留言成功!",Toast.LENGTH_SHORT).show();
                        finish();
                    }
    
    
                }
            });
    
    
        }
    }
    
    

    学生端选课界面 choose_course.java

    package com.example.database_manage.student;
    
    import android.content.ContentValues;
    import android.content.Intent;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.Toast;
    
    import com.example.database_manage.R;
    import com.example.database_manage.database.CommonDatabase;
    
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class choose_course extends AppCompatActivity {
        private SQLiteDatabase db;
        private List<item> arrayList;
        private courseAdapter c;
        private ListView listView_course;
        private Button button_back;
        private Button button_choose;
        private CommonDatabase commonDatabase;
        private Intent intent_3;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_choose_course);
            /////////////////////////////
            commonDatabase = new CommonDatabase();
    
            db =commonDatabase.getSqliteObject(choose_course.this,"test_db");
            /////////////////////////////
            listView_course = findViewById(R.id.listview_course);
            button_back = findViewById(R.id.back);
            button_choose =findViewById(R.id.choose);
            intent_3 = getIntent();
            View.OnClickListener listener_choose =new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId())
                    {
                        case R.id.choose:
                            String string_chongtu = "";
                            for(int i=0;i<c.getCount();i++)
                            {
                                //获取子项的对象
                                item it = (item)c.getItem(i);
    
                                //如果是被选中的状态
                                if(it.ischeck==true)
                                {
                                    //去表中查一下是否已经存在
                                    Cursor cursor = db.query("student_course",null,"student_id =? AND course_name =? AND teacher_name = ?",
                                            new String[]{intent_3.getStringExtra("student_id"),it.getCourse_name(),it.getTeacher_name()},null,null,null);
                                   //如果不存在
                                    if(cursor.getCount()==0)
                                    {
                                        ContentValues values1 = new ContentValues();
                                        ////////////////////////////////
    
                                        values1.put("student_id",intent_3.getStringExtra("student_id"));
                                        values1.put("course_name",it.getCourse_name());
                                        values1.put("teacher_name",it.getTeacher_name());
                                        db.insert("student_course",null,values1);
                                    }
                                    //存在说明已经选过了
                                    else
                                    {
                                        string_chongtu+=it.getCourse_name();
                                        string_chongtu+="/";
                                    }
                                }
                                //如果没有冲突的
                                if(string_chongtu.equals(""))
                                {
                                    Toast.makeText(choose_course.this,"选课成功!",Toast.LENGTH_SHORT).show();
    
                                }
                                else
                                {
                                    Toast.makeText(choose_course.this,string_chongtu+"重复选中,其他课程选课成功!",Toast.LENGTH_SHORT).show();
                                }
    
                            }
    
                            break;
    
                        case R.id.back:
                            finish();
                            break;
                    }
                }
            };
            button_choose.setOnClickListener(listener_choose);
            button_back.setOnClickListener(listener_choose);
    
            //获取课程的全部信息
            Cursor cursor = db.query("course", null, null, null, null, null, null);
    
            arrayList= new ArrayList<item>();
            //对游标进行遍历
            while(cursor.moveToNext())
            {
    
                String  name = cursor.getString(cursor.getColumnIndex("course_name"));
                String  time = cursor.getString(cursor.getColumnIndex("course_time"));
                String  period = cursor.getString(cursor.getColumnIndex("course_period"));
                String  teacher = cursor.getString(cursor.getColumnIndex("teacher_name"));
                String  weight = cursor.getString(cursor.getColumnIndex("course_weight"));
    
                item it = new item(name,time,period,teacher,weight);
                arrayList.add(it);
            }
             //实例化Adapter
             c = new courseAdapter(choose_course.this,arrayList);
    
            listView_course.setAdapter(c);
        }
    }
    
    
    展开全文
  • 今天上课老师让利用ListView和数据库做一个学员信息管理系统。下面我就把自己做的代码复制下来,供大家参考。 首页的布局main.xml xml version="1.0" encoding="utf-8"?> LinearLayout xmlns:android=...
  • 学生信息管理系统Android源码,使用博文https://blog.csdn.net/sinat_34608734/article/details/74136271 给出的代码用Eclipse编译生成的,亲测Android2.2~Android4.2可用,模拟器和真机都运行过,修改了一些导包等...
  • 一、Android实现学生信息管理系统之登录与数据库准备
  • 学生信息管理系统项目源码Android应用源码
  • 非常完美的学生管理系统,保证可以运行,可以用来做毕业设计
  • 自制学生信息管理系统 精美界面 功能1.用户信息注册,密保验证更改密码 2. 学生信息录入,查询,修改,更新 3.仿qq换头像,可以点击用户头像进行头像切换和拍照 4.采用侧滑菜单,recyclerview 与cardview 5.数据库...
  • 基于Android的简单学生信息管理系统,使用了SQLite数据库,可以简单用于学生实验与课程设计的使用。
  • 学生信息管理系统,含完整的源码(jsp和servlet)和数据库。
  • 学生信息管理系统.rar

    2020-07-27 23:31:55
    4.学生信息管理功能: (1)上传学生作业 (2)浏览学生作业 (3)学生下载作业 (4)学生删除作业 管理员: 1.登录:管理员登录 2.专业基础信息的维护:对专家进行增删改查 3.班级基础信息的维护:对班级进行增...
  • Android 学生信息管理系统LinearLayout xmlns:android=
  • 前一阵自学了一些安卓基础,正好需要交数据库大作业,就拿android做了一个简单的学生信息管理系统。 功能设计 登录界面(入口):后台数据库登录密码验证、登录身份选择、修改密码。 学生端:学生可以选课、可以查看...
  • 安卓学生信息管理app

    2020-07-27 23:30:39
    Android studio 开发的学生信息管理app 源代码 课设报告
  • 该系统的具体任务就是设计一个学生管理系统,由计算机来代替人工执行一系列诸如对学生信息的增加、删除、查询和修改的处理操作,以方便对以上信息的管理组织工作。 建立学生管理系统,采用计算机对学生进行管理,...
  • 一个学生信息管理系统,源码完整,可以参考,可以运行
1 2 3 4 5 ... 20
收藏数 7,433
精华内容 2,973
关键字:

学生信息管理系统android