【Android教学用例程序】学生数据库管理2 - 功能设计与实现

功能设计说明:

  1. 创建库和表: 点击后会创建数据库 school.db ,然后建立基本表 Student 。 Student结构:id int primary key,name string,age int。 注意:数据库只建立一次。修改版本号后,可更新,但会清除数据。
  2. 初始化:填入五个基本数据,便于用户测试。 如果id冲突,内容会插入失败。简单起见,未做提示。
  3. 显示内容:显示数据库中所有数据。也就是 select * from Student。
  4. 增加:三项值全部输入,才能写入数据库,并且保证数值类型正确。如果id冲突,插入会失败。插入后,点击显示全部,可以看到新数据。
  5. 删除:填写列表中存在的id,本删除操作根据id号进行删除。
  6. 修改:要求同“增加”。
  7. 查询:仅能够根据id进行查询。

程序结构如下:

 

MainActivity.java

package com.example.sqlitestudent;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;//定义RecyclerView控件
    private RecyclerView.Adapter mAdapter;//定义RecyclerView控件的适配器
    private RecyclerView.LayoutManager mLayoutManager;//定义RecyclerView控件的布局管理器
    private DBHelper dbHelper;    //用于创建帮助器对象(处理数据库相关操作)
    private SQLiteDatabase database;    //用于创建数据库对象

    Button btnCreate, btnInit, btnList, btnInsert, btnDelete, btnUpdate, btnQuery;//定义七个按钮
    EditText editTextID;//定义三个编辑对话框
    EditText editTextName;
    EditText editTextAge;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);//禁止软键盘打开界面时自动跳出

        btnCreate = (Button) findViewById(R.id.db_create);//xml定义的控件与程序定义的变量绑定
        btnInit   = (Button) findViewById(R.id.db_init);
        btnList   = (Button) findViewById(R.id.db_list);
        btnInsert = (Button) findViewById(R.id.db_insert);
        btnDelete = (Button) findViewById(R.id.db_delete);
        btnUpdate = (Button) findViewById(R.id.db_update);
        btnQuery  = (Button) findViewById(R.id.db_query);

        editTextName = (EditText) findViewById(R.id.stu_name);
        editTextID   = (EditText) findViewById(R.id.stu_no);
        editTextAge  = (EditText) findViewById(R.id.stu_age);
        editTextID.setCursorVisible(false);//取消编辑控件闪烁效果
        editTextAge.setCursorVisible(false);
        editTextName.setCursorVisible(false);

        btnCreate.setOnClickListener(lisenter);//设置按钮的侦听器
        btnInit.setOnClickListener(lisenter);
        btnList.setOnClickListener(lisenter);
        btnInsert.setOnClickListener(lisenter);
        btnDelete.setOnClickListener(lisenter);
        btnUpdate.setOnClickListener(lisenter);
        btnQuery.setOnClickListener(lisenter);
}


    private View.OnClickListener lisenter = new View.OnClickListener() {//侦听器
        @Override
        public void onClick(View view) {
            Button button = (Button) view;//把点击获得的参数传递给button
            try{
                switch (button.getId()) {//根据按钮id,判断点击了那个按钮,进一步执行相关代码
                    case R.id.db_create: {                        //create Database
                        dbHelper = new DBHelper(MainActivity.this, "school.db", null, 3);//创建帮助器对象
                        database = dbHelper.getWritableDatabase();//创建数据库对象
                        Toast.makeText(MainActivity.this,"数据库已建立",Toast.LENGTH_SHORT).show();
                        database.close();
                        break;
                    }
                    case R.id.db_init: {                        //Init Table
                        Toast.makeText(MainActivity.this,"新写入5条数据",Toast.LENGTH_SHORT).show();
                        database = dbHelper.getWritableDatabase();
                        dbHelper.onInit(database);
                        database.close();
                        break;
                    }
                    case R.id.db_list: {                        //Show all data
                        Toast.makeText(MainActivity.this,"显示全部数据",Toast.LENGTH_SHORT).show();
                        initDbData();//重新初始化RecyclerView
                        initView();
                        break;
                    }
                    case R.id.db_insert:{                        //Insert one line data
                        Toast.makeText(MainActivity.this,"插入一条数据",Toast.LENGTH_SHORT).show();
                        database = dbHelper.getWritableDatabase();
                        int InsertId,InsertAge;
                        String InsertName;
                        InsertId = Integer.parseInt(editTextID.getText().toString());
                        InsertName = editTextName.getText().toString();
                        InsertAge = Integer.parseInt(editTextAge.getText().toString());
                        // 此处应增加:if 符合条件,才能插入数据。else 提示数据不符合要求。
                        dbHelper.onInsert(database,InsertId, InsertName,InsertAge);
                        database.close();
                        break;
                    }
                    case R.id.db_delete:{                        //Delete the selected data
                        Toast.makeText(MainActivity.this,"删除一条数据",Toast.LENGTH_SHORT).show();
                        database = dbHelper.getWritableDatabase();
                        int DeleteId;
                        DeleteId = Integer.parseInt(editTextID.getText().toString());
                        // 应增加:if 符合条件,才能删除数据。else 提示数据不符合要求。
                        dbHelper.onDelete(database,DeleteId);
                        database.close();
                        break;
                    }
                    case R.id.db_update:{                        //Update the selected data
                        Toast.makeText(MainActivity.this,"更新一条数据",Toast.LENGTH_SHORT).show();
                        database = dbHelper.getWritableDatabase();
                        int UpdateId,UpdateAge;
                        String UpdateName;
                        UpdateId = Integer.parseInt(editTextID.getText().toString());
                        UpdateName = editTextName.getText().toString();
                        UpdateAge = Integer.parseInt(editTextAge.getText().toString());
                        Log.d("sql test update:", UpdateName);
                        // 应增加:if 符合条件,才能更新数据。else 提示数据不符合要求。
                        dbHelper.onUpdate(database,UpdateId, UpdateName,UpdateAge);
                        database.close();
                        break;
                    }
                    case R.id.db_query:{                        //Query target data
                        Toast.makeText(MainActivity.this,"查询当前学号学生",Toast.LENGTH_SHORT).show();
                        initLineData();//重新初始化RecyclerView
                        initView();
                        break;
                    }
                    default:
                        break;
                }
            }
            catch(Exception e)
            {
            }
        }
    };

    private void initDbData() {// 初始化RecyclerView数据,把数据库内容写入
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mAdapter = new MyAdapter(getStudentList());
    }
    private void initLineData() {// 初始化RecyclerView数据,把数据库一条查询结果写入
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mAdapter = new MyAdapter(getStudentLine());
    }
    private void initView() {// 设置RecyclerView适配器
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);        // 设置布局管理器
        mRecyclerView.setLayoutManager(mLayoutManager);        // 设置adapter
        mRecyclerView.setAdapter(mAdapter);
    }

    public ArrayList<Student>  getStudentList() {//获取全部数据
        dbHelper = new DBHelper(MainActivity.this, "school.db", null, 3);//This is the key. 2017.6.21 4:10 AM
        database = dbHelper.getWritableDatabase();
        Cursor cursor= dbHelper.onList(database);//游标记录数据集
        ArrayList<Student> studentList = new ArrayList<Student>();//对象数组,用于接收游标的数值
        if (cursor.moveToFirst()) {
            do {
                Student student = new Student();
                student.student_ID = Integer.parseInt(cursor.getString(cursor.getColumnIndex(Student.KEY_ID)) );
                student.name = cursor.getString(cursor.getColumnIndex(Student.KEY_name));
                student.age = Integer.parseInt(cursor.getString(cursor.getColumnIndex(Student.KEY_age)));
                studentList.add(student);
            } while (cursor.moveToNext());
        }
        cursor.close();
        database.close();
        return studentList;
    }

    public ArrayList<Student>  getStudentLine() {// 处理查询结果,类似获取全部数据
        dbHelper = new DBHelper(MainActivity.this, "school.db", null, 3);
        database = dbHelper.getWritableDatabase();

        ArrayList<Student> studentLine = new ArrayList<Student>();
        int QueryId = Integer.parseInt(editTextID.getText().toString());
        Cursor cursor = dbHelper.onQuery(database,QueryId);
        if (cursor.moveToFirst()) {
            do {
                Student student = new Student();
                student.student_ID = Integer.parseInt(cursor.getString(cursor.getColumnIndex(Student.KEY_ID)) );
                student.name = cursor.getString(cursor.getColumnIndex(Student.KEY_name));
                student.age = Integer.parseInt(cursor.getString(cursor.getColumnIndex(Student.KEY_age)));
                studentLine.add(student);
            } while (cursor.moveToNext());
        }
        cursor.close();
        database.close();
        return studentLine;
    }
}

 

MyAdapter.java

package com.example.sqlitestudent;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

/** * RecyclerView Adapter .  Created by David on 2017/6/20. */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{

    private ArrayList<Student> mData;
    public MyAdapter(ArrayList<Student> data) {
        this.mData = data;
    }

    public void updateData(ArrayList<Student> data) {
        this.mData = data;
        notifyDataSetChanged();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_stu, parent, false);// 实例化展示的view
        ViewHolder viewHolder = new ViewHolder(v);// 实例化viewholder
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        //holder.mTv.setText(mData.get(position));// 绑定数据
        Student student = mData.get(position);
        holder.tvAge.setText(student.age+"");//注意数据类型
        holder.tvName.setText(student.name);
        holder.tvID.setText(student.student_ID+"");
    }

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvID,tvName,tvAge;
        public ViewHolder(View itemView) {
            super(itemView);
            tvID = (TextView) itemView.findViewById(R.id.item_stuID);
            tvName = (TextView) itemView.findViewById(R.id.item_stuName);
            tvAge = (TextView) itemView.findViewById(R.id.item_stuAge);
        }
    }
}

DBHelper.java

package com.example.sqlitestudent;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DBHelper  extends SQLiteOpenHelper {
    //version number to upgrade database version //each time if you Add, Edit table, you need to change the version number.
    public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {//建立数据库
        String CREATE_TABLE_STUDENT = "CREATE TABLE " + Student.TABLE  + "("
                + Student.KEY_ID  + " INTEGER PRIMARY KEY ,"
                + Student.KEY_name + " TEXT, "
                + Student.KEY_age + " INTEGER )";
        db.execSQL(CREATE_TABLE_STUDENT);
    }

    public void onInit(SQLiteDatabase db) {//向数据库学生表中添加5名学生,初始化数据。
        db.execSQL("insert into " + Student.TABLE + "("+ Student.KEY_ID+","+Student.KEY_name+","+Student.KEY_age+")" + " values(?, ?, ?)", new Object[]{101,"刘得意", 19});
        db.execSQL("insert into " + Student.TABLE + "("+ Student.KEY_ID+","+Student.KEY_name+","+Student.KEY_age+")" + " values(?, ?, ?)", new Object[]{102,"王锐", 20});
        db.execSQL("insert into " + Student.TABLE + "("+ Student.KEY_ID+","+Student.KEY_name+","+Student.KEY_age+")" + " values(?, ?, ?)", new Object[]{103,"何煜中", 19});
        db.execSQL("insert into " + Student.TABLE + "("+ Student.KEY_ID+","+Student.KEY_name+","+Student.KEY_age+")" + " values(?, ?, ?)", new Object[]{104,"王磊", 21});
        db.execSQL("insert into " + Student.TABLE + "("+ Student.KEY_ID+","+Student.KEY_name+","+Student.KEY_age+")" + " values(?, ?, ?)", new Object[]{105,"冯松", 19});
    }
    public Cursor onList(SQLiteDatabase db) {//查询全部数据
        String selectQuery =  "SELECT  " + Student.KEY_ID + "," +  Student.KEY_name + "," +  Student.KEY_age +
                " FROM " + Student.TABLE;
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
         }

    public void onInsert(SQLiteDatabase db, int id, String name, int age) {//向学生表中添加1名学生。
        db.execSQL("insert into " + Student.TABLE + "("+ Student.KEY_ID+","+Student.KEY_name+","+Student.KEY_age+")" +
                    " values(?, ?, ?)", new Object[]{id,name,age});
    }
    public void onDelete(SQLiteDatabase db, int id) {//从学生表删除1名学生。
        db.execSQL("delete from " + Student.TABLE + " where "+ Student.KEY_ID + " = "+ id);
    }
    public void onUpdate(SQLiteDatabase db, int id, String name, int age) {//从学生表删除1名学生。
        db.execSQL(" update " + Student.TABLE +" " +
                    " set "+ Student.KEY_ID + " = " + id + "," + Student.KEY_name + " = '" + name + "'," + Student.KEY_age + " = " + age +
                    " where "+ Student.KEY_ID + " = "+ id );
    }
    public Cursor onQuery(SQLiteDatabase db, int id) {//通过id查询学生
        Cursor cursor;
        String selectQuery =  "SELECT  " + Student.KEY_ID + "," +  Student.KEY_name + "," +  Student.KEY_age +
                " FROM " + Student.TABLE + " where "+ Student.KEY_ID + " = "+ id;
        cursor = db.rawQuery(selectQuery,null);
        return cursor;
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//更新数据库
        db.execSQL("DROP TABLE IF EXISTS " + Student.TABLE);// Drop older table if existed, all data will be gone!!!
        onCreate(db);// Create tables again
    }
}

Student.java

package com.example.sqlitestudent;
public class Student {
    public static final String TABLE = "Student";// Labels table name
    public static final String KEY_ID = "id";// Labels Table Columns names
    public static final String KEY_name = "name";
    public static final String KEY_age = "age";

    public int student_ID;// property help us to keep data
    public String name;
    public int age;
}

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.example.sqlitestudent"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:recyclerview-v7:26.+'
    debugCompile 'com.amitshekhar.android:debug-db:1.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    testCompile 'junit:junit:4.12'

}

 

posted on 2017-06-21 16:38  HBU_DAVID  阅读(293)  评论(0编辑  收藏  举报

导航