LinearLayout ="http://schemas.android.com/apk/res/android" android:ori_android。学生需管理的信息包含:学号、姓名、专业、身份证号、监护人、">
当前位置:   article > 正文

Android 学生信息管理系统_android。学生需管理的信息包含:学号、姓名、专业、身份证号、监护人、

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. <group android:checkableBehavior="single">
  3. <item android:id="@+id/delete" android:title="删除学员信息" />
  4. <item android:id="@+id/look" android:title="详细信息" />
  5. <item android:id="@+id/add" android:title="添加学员信息" />
  6. <item android:id="@+id/write" android:title="修改学员信息" />
  7. </group>
  8. </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. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.TextView;
  7. import cn.yj3g.student.entry.Student;
  8. import cn.yj3g.student.entry.TableContanst;
  9. public class ShowStudentActivity extends Activity {
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.student_info);
  14. Intent intent = getIntent();
  15. Student student = (Student) intent.getSerializableExtra(TableContanst.STUDENT_TABLE);
  16. ((TextView)findViewById(R.id.tv_info_id)).setText(student.getId()+"");
  17. ((TextView)findViewById(R.id.tv_info_name)).setText(student.getName());
  18. ((TextView)findViewById(R.id.tv_info_age)).setText(student.getAge()+"");
  19. ((TextView)findViewById(R.id.tv_info_sex)).setText(student.getSex());
  20. ((TextView)findViewById(R.id.tv_info_likes)).setText(student.getLike());
  21. ((TextView)findViewById(R.id.tv_info_train_date)).setText(student.getTrainDate());
  22. ((TextView)findViewById(R.id.tv_info_phone)).setText(student.getPhoneNumber());
  23. }
  24. public void goBack(View view) {
  25. finish();
  26. }
  27. }

界面效果如下:

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

界面效果如下:

修改界面:

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

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

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

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


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


原文地址:  http://www.cnblogs.com/zxl-jay/archive/2011/09/21/2182890.html#2302140


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/616182
推荐阅读
相关标签
  

闽ICP备14008679号