Android实现学生信息管理系统之登录与数据库准备

前言

前一阵自学了一些安卓基础,正好需要交数据库大作业,就拿android做了一个简单的学生信息管理系统。
Android学生信息管理系统

功能设计

登录界面(入口):后台数据库登录密码验证、登录身份选择、修改密码。

学生端:学生可以选课、可以查看选课结果、查看个人信息、向老师和管理员提出建议、切换账户。

教师端:查看所教课程信息、管理所教学生成绩、查看学生留言(匿名)、统计学生信息、查看教师个人信息。

管理员端:查询、管理学生、教师、管理员、课程信息,对学生绩点按照条件排序、查看留言,并且可以看到留言人的信息。

后台:Sqlite数据库,表的基本设计,触发器、外键依赖、约束等保证表的合理性、完整性,对于账户的md5加密算法设计

一、数据库表设计

先来看看总体的E-R图,可能设计的不太好,大家仅供参考。
在这里插入图片描述

package com.example.database_manage.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/*
   该界面主要用于建表,以及设定完整性
 */
public class DBOpenHelper extends SQLiteOpenHelper {

        //带全部参数的构造函数,此构造函数必不可少
        public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {

            //学生信息
            String sql_student = "create table student(" +
                    "id int primary key not null ," +
                    "name varchar(20) not null," +
                    "sex varchar(10) not null,"+
                    "age int check(age<100 and age>0),"+
                    "banji varchar(20) ,"+
                    "phone int ,"+
                    "college varchar(20) default '无'," +
                    "jidian int check(jidian>0 and jidian<5.0)) "
                    ;
            //学生——登陆密码表
            String sql_student_load = "create table load_account(account int primary Key not null ,password varchar(20))";
			//触发器
            String sql_ctrigger = "CREATE TRIGGER load_add AFTER INSERT ON student  " +
                    "BEGIN INSERT INTO load_account(account,password) VALUES (new.id,'e10adc3949ba59abbe56e057f20f883eWYH'); END;";
            String sql_trigger = "CREATE TRIGGER delete_load BEFORE DELETE ON student BEGIN DELETE  FROM load_account WHERE account =old.id ;END ; ";
            String sql_trigger2 = "CREATE TRIGGER student_load_change " +
                    " AFTER UPDATE ON student BEGIN UPDATE  load_account SET ACCOUNT = NEW.ID WHERE ACCOUNT = OLD.ID; END;";
            db.execSQL(sql_student_load);
            db.execSQL(sql_student);
            db.execSQL(sql_ctrigger);
            db.execSQL(sql_trigger);
            db.execSQL(sql_trigger2);


            //老师个人信息表
            String sql_teacher ="create table teacher(" +
                    "teacher_id int primary key not null," +
                    "name varchar(20)," +
                    "sex  varchar(20) check(sex = '男' or sex = '女')," +

                    "age int check(age>0 and age<100)," +
                    "level varchar(20)," +
                    "phone int ," +
                    "college varchar(20))";
            //老师登录信息表
            String sql_teacher_load = "create table load_teacher(" +
                    "account int primary key not null ," +
                    "password varchar(20))";
			//触发器
            String sql_ttrigger = "CREATE TRIGGER load_add_teacher AFTER INSERT ON teacher  " +
                    "BEGIN INSERT INTO load_teacher(account,password) VALUES (new.teacher_id,'e10adc3949ba59abbe56e057f20f883eWYH'); END;";
            String sql_dttrigger = "CREATE TRIGGER delete_teacher_load " +
                    " BEFORE DELETE ON teacher BEGIN DELETE FROM load_teacher WHERE ACCOUNT = OLD.TEACHER_ID; END;";
            String sql_dttrigger1 = "CREATE TRIGGER teacher_load_change " +
                    " AFTER UPDATE ON teacher BEGIN UPDATE  load_teacher SET ACCOUNT = NEW.TEACHER_ID WHERE ACCOUNT = OLD.TEACHER_ID; END;";

            db.execSQL(sql_teacher_load);
            db.execSQL(sql_teacher);
            db.execSQL(sql_ttrigger);
            db.execSQL(sql_dttrigger);
            db.execSQL(sql_dttrigger1);


            //学生选课信息表
            String sql_student_course = "create table student_course(" +
                    "student_id int ,"+
                    "course_name varchar(20),"+
                    "teacher_name varchar(10),"+
                    "score int, " +
                    "FOREIGN KEY(course_name) REFERENCES course(course_name)," +
                    "FOREIGN KEY(teacher_name) REFERENCES course(teacher_name)" +

                    ")";
            //课程信息表
            String sql_course = "create table course(" +
                    "teacher_name varchar(20) not null,"+
                    "course_name varchar(20) not null," +
                    "course_weight SMALLINT ,"+
                    "course_time varchar(20)," +
                    "course_period varchar(20)," +
                    "primary key(teacher_name,course_name)," +
                    "FOREIGN KEY(teacher_name) REFERENCES teacher(name))";
            db.execSQL(sql_course);
            db.execSQL(sql_student_course);


			//留言信息存储表
            String sql_liuyan  = "create table message(" +
                    "student_id int primary key not null," +
                    "message text)";
            db.execSQL(sql_liuyan);



            //管理员表
            String sql_admin = "create table administractor(" +
                    " account varchar(20)," +
                    " password varchar(20))";
            String sql_insert_admin = "insert into administractor values('WYH','c7533ad5fb828c1bedd12608f86f998dWYH')";

            db.execSQL(sql_admin);
            db.execSQL(sql_insert_admin);

       
            //个人资源配置表,比如更改图片之类的啦
            String personal_resource = "create table personal_resource(" +
                    "id int primary key not null ," +
                    "IMAGE blob)";

            db.execSQL(personal_resource);

            //触发器

            String personal_resource_trigger = "CREATE TRIGGER personal_resource_trigger AFTER INSERT ON student " +
                    "BEGIN INSERT INTO personal_resource(id,IMAGE) VALUES (new.id,null);END;";
            String personal_resource_trigger1 = "CREATE TRIGGER personal_resource_trigger_t AFTER INSERT ON teacher " +
                    "BEGIN INSERT INTO personal_resource(id,IMAGE) VALUES (new.teacher_id,null);END;";

            db.execSQL(personal_resource_trigger);
            db.execSQL(personal_resource_trigger1);



			//插入基本测试数据
            String sql_insert1 = "insert into course(teacher_name,course_name,course_weight,course_time,course_period) values('李xx','电子线路基础',2,'周一上午','1')";
            String sql_insert2 = "insert into course(teacher_name,course_name,course_weight,course_time,course_period) values('高x* 刘x','大学英语4',4,'周五上午','1')";
            String sql_insert3 = "insert into course(teacher_name,course_name,course_weight,course_time,course_period) values('魏xx','数据库原理',3,'周三上午','1')";
            String sql_insert4 = "insert into course(teacher_name,course_name,course_weight,course_time,course_period) values('司xx','数学模型',2,'周一晚上','1')";
            String sql_insert5 = "insert into course(teacher_name,course_name,course_weight,course_time,course_period) values('司xx','运筹学',2,'周三下午','1')";
            String sql_insert6 = "insert into course(teacher_name,course_name,course_weight,course_time,course_period) values('王xx','毛泽东思想概论',4.5,'周五晚上','1')";
            db.execSQL(sql_insert1);
            db.execSQL(sql_insert2);
            db.execSQL(sql_insert3);
            db.execSQL(sql_insert4);
            db.execSQL(sql_insert5);
            db.execSQL(sql_insert6);




			//插入基本测试数据
            String sql_p = "insert into student(id ,name ,sex,age ,banji , phone, college )" +
                    " values(20171302028,'武xx','男',19,'17计科3班',188330,'网络空间安全与计算机学院')";

            String sql_p1 = "insert into student(id ,name ,sex,age ,banji , phone, college )" +
                    " values(20180301178,'梁x','女',20,'18新闻2班',188330,'新闻传播学院')";
            String sql_p2 = "insert into student(id ,name ,sex,age ,banji , phone, college )" +
                    " values(20171302029,'台x','男',20,'17计科3班',188330,'网络空间安全与计算机学院')";
            String sql_p3 = "insert into student(id ,name ,sex,age ,banji , phone, college )" +
                    " values(20171302030,'王x','男',20,'17计科3班',188330,'网络空间安全与计算机学院')";
            String sql_p4 = "insert into student(id ,name ,sex,age ,banji , phone, college )" +
                    " values(20171302031,'霍xx','男',20,'17材料2班',188330,'化学与环境科学学院')";
            String sql_p5 = "insert into student(id ,name ,sex,age ,banji , phone, college )" +
                    " values(20171102027,'王xx','男',20,'17材料2班',18812141604,'化学与环境科学学院')";


            String sql_tp1 = "insert into teacher(teacher_id ,name ,sex,age ,level , phone, college )" +
                    " values(2018,'魏xx','男',20,'高级教师',188330,'网络空间安全与计算机学院')";
            String sql_tp = "insert into teacher(teacher_id ,name ,sex,age ,level , phone, college )" +
                    " values(2017,'司xx','男',19,'高级教师',188330,'网络空间安全与计算机学院')";
            db.execSQL(sql_p);
            db.execSQL(sql_tp);
            db.execSQL(sql_p1);
            db.execSQL(sql_p2);
            db.execSQL(sql_p3);
            db.execSQL(sql_p4);
            db.execSQL(sql_p5);
            db.execSQL(sql_tp1);


        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }

    }


为了能够快速简单的获取SQLitedatabase对象,设计一个公用类方法

CommonDatabase.java

package com.example.database_manage.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

public class CommonDatabase {
    private DBOpenHelper dbHelper;
    private SQLiteDatabase sqlite;
    public SQLiteDatabase getSqliteObject(Context context, String db_name){
        dbHelper = new DBOpenHelper(context,db_name,null,1);
        sqlite = dbHelper.getWritableDatabase();
        return sqlite;
    }

}

我们的登录信息在数据库应该以密文显示,所以我们应该使用一种加密算法,在这里我选择了不可逆的md5算法。然后再登录的时候将密码用md5转换后再与数据库中进行比较。

MD5demo.java

package com.example.database_manage.database;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Demo {
    private  static  String key = "WYH";

    //写一个md5加密的方法
    public static String md5(String plainText) {
        //定义一个字节数组
        byte[] secretBytes = null;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //对字符串进行加密
            md.update(plainText.getBytes());
            //获得加密后的数据
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法!");
        }
        //将加密后的数据转换为16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位,需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code+key;
    }

}

虽然md5算法是不可逆的,但是网上依旧有解密网站,但是解密网站相当于是一个大量存储这种转换信息的数据库,并不是真正的解密了。
网址如下:
https://www.cmd5.com/
它只能解密一些简单的诸如123456789这种密码,但是这里我的初始密码确实是123456,所以我在最后返回的md5密文后增加一个key,如上面代码所示,相当于增加了个人标记。

二、登录界面与逻辑设计

效果如图所示
在这里插入图片描述
登录布局代码

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

    tools:context=".start_load.load">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:text="河北大学学生信息系统"
        android:textSize="30dp" />

    <ImageView

        android:layout_width="150dp"
        android:layout_height="150dp"
        app:srcCompat="@mipmap/school_new"
        android:layout_marginTop="60dp"
        android:layout_gravity="center_horizontal"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="50dp">

        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_gravity="center"
            android:layout_marginLeft="80dp"
            android:src="@mipmap/geren"/>

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:hint="请输入您的学号"
                android:id="@+id/input_id"

                android:layout_marginRight="50dp"
                android:layout_height="wrap_content">
                <EditText
                    android:id="@+id/edit_load_zhanghao"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="20sp"
                    />

            </android.support.design.widget.TextInputLayout>


    </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"


            android:orientation="horizontal">

            <ImageView
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginLeft="80dp"
                android:layout_gravity="center"
                android:src="@mipmap/suo"/>
            <RelativeLayout
                android:layout_marginRight="50dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
            <android.support.design.widget.TextInputLayout
                app:errorEnabled="true"
                app:counterMaxLength="10"
                app:counterEnabled="true"
                android:id="@+id/textinput_p"
                android:hint="请输入您的密码"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                    <EditText
                        android:id="@+id/edit_load_password"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textSize="20dp"
                        />

            </android.support.design.widget.TextInputLayout>
                <ImageButton
                    android:id="@+id/imagebutton"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:background="#00000000"
                    android:layout_alignParentEnd="true"
                    android:src="@drawable/invisible" />
                </RelativeLayout>


        </LinearLayout>
    <RelativeLayout
        android:layout_marginRight="50dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:id="@+id/checkbox_remember"
            android:text="记住密码"/>

    </RelativeLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="30dp"
        >
        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/load_radiogroup"
            android:gravity="center"
            android:orientation="horizontal">

                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="学生"

                    android:id="@+id/radiobutton_xuesheng"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/radiobutton_teacher"
                android:text="老师"/>
                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/radiobutton_guanliyuan"
                    android:text="管理员"/>

        </RadioGroup>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginTop="30dp"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="登录"
            android:background="@drawable/button_background"
            android:textColor="#ffffffff"


            android:id="@+id/button_load"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="修改密码"
            android:textColor="#ffffffff"
            android:background="@drawable/button_background"


            android:id="@+id/button_change_password"/>
    </LinearLayout>




</LinearLayout>

说明:这里我使用了design库的TextInputLayout,觉得好看的可以参考我这篇文章
TextInputLayout 使用及其属性

处理登录的逻辑代码

package com.example.database_manage.start_load;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.database_manage.R;
import com.example.database_manage.administractor.Container;
import com.example.database_manage.database.CommonDatabase;
import com.example.database_manage.student.activity_student;
import com.example.database_manage.teacher.activity_teacher;

import static com.example.database_manage.database.MD5Demo.md5;


/***
 * 登陆界面的配置
 */
public class load extends AppCompatActivity {

    //标记是选择了学生还是管理员
    private String state = "";
    private SQLiteDatabase db ;
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private CheckBox rememberPass;
    private boolean isRemember ;
    private EditText edit_load_zhanghao;
    private EditText edit_load_password;


    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load);

        //用于记住密码的实现
        rememberPass = findViewById(R.id.checkbox_remember);

        pref = PreferenceManager.getDefaultSharedPreferences(this);

        isRemember = pref.getBoolean("remember_password",false);


        //状态栏融为一体的方法,这里参考了郭神的博客
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }


        //轮子TextputLayout
        final TextInputLayout textInputLayout_p = findViewById(R.id.textinput_p);

        final TextInputLayout textInputLayout_id = findViewById(R.id.input_id);

        //账号密码编辑框
        edit_load_zhanghao = findViewById(R.id.edit_load_zhanghao);

        edit_load_password = findViewById(R.id.edit_load_password);
        //获取数据库对象
        CommonDatabase commonDatabase = new CommonDatabase();

        db =commonDatabase.getSqliteObject(load.this,"test_db");

        //绑定组件
        final Button button_change_password = findViewById(R.id.button_change_password);

        RadioGroup load_radiogroup = findViewById(R.id.load_radiogroup);

        final ImageButton imageButton = findViewById(R.id.imagebutton);

        //眼睛睁开闭上
        edit_load_password.setTransformationMethod(PasswordTransformationMethod.getInstance());//初始为隐藏密文状态

        imageButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN) //按下重新设置背景图片

                {

                    ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.visible));
                    edit_load_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());//显示


                }

                else if(event.getAction() == MotionEvent.ACTION_UP) //松手恢复原来图片

                {

                    ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.invisible));
                    edit_load_password.setTransformationMethod(PasswordTransformationMethod.getInstance());//隐藏

                }
                return false;
            }
        });


        //单选按钮监听器
        load_radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (group.getCheckedRadioButtonId())
                {
                    case R.id.radiobutton_xuesheng:

                    textInputLayout_id.setHint("请输入您的学号");
                        button_change_password.setVisibility(View.VISIBLE);
                        state = "student";
                        break;
                    case R.id.radiobutton_guanliyuan:

                        textInputLayout_id.setHint("请输入您的账号");
                        state = "guanliyuan";
                        break;
                    case R.id.radiobutton_teacher:

                        textInputLayout_id.setHint("请输入您的账号");
                        state = "teacher";
                        break;
                     default:
                         break;

                }
            }
        });

        //登录按钮
        Button button_load = findViewById(R.id.button_load);
        button_load.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //获取学生输入的账号密码
                String account_load = edit_load_zhanghao.getText().toString();
                
                //由于我们在数据库中是密文存储的所以这里也要用我们写好的md5方法取转换成密文进行匹配验证
                String password_load = md5(edit_load_password.getText().toString());
                if(state=="guanliyuan")
                {
                    String true_password="";

                    Cursor cursor = db.query("administractor", null, "account = ?", new String[]{account_load}, null, null, null);

                    while(cursor.moveToNext())
                    {
                        true_password =cursor.getString(cursor.getColumnIndex("password"));
                    }

                    if(password_load.equals(true_password))
                    {
                        isr();
                        startActivity(new Intent(load.this, Container.class));
                        Toast.makeText(load.this,"登陆成功",Toast.LENGTH_SHORT).show();
                        finish();
                    }
                    else
                    {
                        Toast.makeText(load.this,"密码错误!",Toast.LENGTH_SHORT).show();
                    }
                }
                else if(state.equals("student"))
                {

                    //去数据库中找账号为account的数据

                    String true_password="";

                    Cursor cursor = db.query("load_account", null, "account = ?", new String[]{account_load}, null, null, null);

                    while(cursor.moveToNext())
                    {
                         true_password =cursor.getString(cursor.getColumnIndex("password"));
                    }

                    if(password_load.equals(true_password)&&true_password.equals("")==false)
                    {
                        isr();
                        Intent intent = new Intent(load.this, activity_student.class);
                        
                        intent.putExtra("student_id",account_load);
                        
                        startActivity(intent);
                        
                        Toast.makeText(load.this,"登陆成功!",Toast.LENGTH_SHORT).show();

                        finish();
                    }
                    else
                    {
                        Toast.makeText(load.this,"密码错误!",Toast.LENGTH_SHORT).show();
                    }

                }
                else if(state.equals("teacher"))
                {
                    //去数据库中找账号为account的数据
                    Cursor cursor = db.query("load_teacher", null, "account = ? AND password = ?", new String[]{account_load,password_load}, null, null, null);



                    if(cursor.getCount()==0)
                    {

                        Toast.makeText(load.this,"密码错误!",Toast.LENGTH_SHORT).show();

                    }
                    else
                    {
                        isr();
                        
                        //登录成功转到老师界面并携带老师的教师号过去
                        Intent intent = new Intent(load.this, activity_teacher.class);
                        
                        intent.putExtra("teacher_id",edit_load_zhanghao.getText().toString());
                        
                        startActivity(intent);
                        
                        Toast.makeText(load.this,"登陆成功!",Toast.LENGTH_SHORT).show();

                        finish();
                    }


                }
                else
                {
                    Toast.makeText(load.this,"您还没有选择任何登录类型!",Toast.LENGTH_SHORT).show();
                }



            }
        });
        //点击修改按钮进入更改密码的界面

        button_change_password.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(load.this, password_change.class);
                startActivity(intent);



            }
        });
        edit_load_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(edit_load_password.getText().toString().equals(""))
                {
                    textInputLayout_p.setError("不能为空!");
                }
                else
                {
                    if(textInputLayout_p.getCounterMaxLength()<edit_load_password.length())
                    {
                        textInputLayout_p.setError("超出字数限制!");
                    }
                    else
                    {
                        textInputLayout_p.setErrorEnabled(false);
                    }
                }


            }
        });
        //如果手机有记录
        if(isRemember)
        {
            edit_load_zhanghao.setText(pref.getString("account",""));
            edit_load_password.setText(pref.getString("password",""));

            //
            rememberPass.setChecked(true);
        }


    }
    //用于实现记住密码的方法,这里使用SharedPreference存放临时数据
    private void isr()
    {
        editor = pref.edit();
        //检查复选框是否被选中
        if(rememberPass.isChecked())
        {
            editor.putBoolean("remember_password",true);
            editor.putString("account",edit_load_zhanghao.getText().toString());
            editor.putString("password",edit_load_password.getText().toString());
        }
        else
        {
            editor.clear();
        }
        editor.apply();
    }

}

修改密码功能实现

修改密码页面
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:background="@drawable/b2"
    android:orientation="vertical"
    tools:context=".start_load.password_change">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginTop="120dp"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30dp"
            android:layout_marginLeft="40dp"
            android:text="身份"/>
        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/password_radiogroup"
            android:gravity="center"

            android:orientation="horizontal">

            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="学生"

                android:id="@+id/radiobutton_xuesheng_p"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:id="@+id/radiobutton_teacher_p"
                android:text="老师"/>
            
        </RadioGroup>
    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="40dp"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="账号"
            android:textSize="30dp"
            android:layout_marginLeft="40dp"/>


        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_c_account"
            android:hint="请输入您的账号"
            android:layout_marginLeft="60dp"
            android:layout_marginRight="20dp"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="40dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="原密码"
            android:textSize="30dp"

            android:layout_marginLeft="40dp"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_c_oldpassword"
            android:hint="请输入您的旧密码"
            android:inputType="textPassword"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="20dp"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="40dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="新密码"
            android:textSize="30dp"
            android:layout_marginLeft="40dp"/>
        <android.support.design.widget.TextInputLayout
            app:errorEnabled="true"
            app:counterMaxLength="10"
            app:counterEnabled="true"
            android:id="@+id/textinput_newpassword"
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:layout_height="wrap_content">
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/et_c_newpassword"
                android:hint="请输入您的新密码"
                android:inputType="textPassword"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="20dp"/>
        </android.support.design.widget.TextInputLayout>


    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="40dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="新密码"
            android:textSize="30dp"
            android:layout_marginLeft="40dp"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/et_c_confirm_newpassword"
            android:hint="请再次确认新密码"
            android:layout_marginLeft="30dp"
            android:inputType="textPassword"
            android:layout_marginRight="20dp"/>
    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_change_password_ok"
        android:layout_gravity="center"
        android:layout_marginTop="40dp"
        android:background="#96B8D1"
        android:textSize="30dp"
        android:text="OK"/>



</LinearLayout>

逻辑代码password_change.java

package com.example.database_manage.start_load;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.database_manage.R;
import com.example.database_manage.database.CommonDatabase;

import static com.example.database_manage.database.MD5Demo.md5;


/***
 * 用于学生/老师修改密码
 */

public class password_change extends AppCompatActivity {
    private  SQLiteDatabase db;
    private  Button button_change;
    private  RadioGroup load_radiogroup;
    private  EditText edit_account;
    private  EditText edit_oldpassword ;
    private  EditText edit_newpassword ;
    private  EditText edit_confirm ;
    private  String true_password ="";
    private  String state = "";
    private  TextInputLayout textInputLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_password_change);

        initView();

        //当选择不同身份时,state标记选择的身份
        load_radiogroup.setOnCheckedChangeListener(
                new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch (group.getCheckedRadioButtonId())
                        {
                            case R.id.radiobutton_xuesheng_p:

                                state="student";

                                break;
                            case R.id.radiobutton_teacher_p:

                                state = "teacher";
                                break;
                        }


                    }
                });

        //为按钮设置监听器
        button_change.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(state.equals("student"))
                    {
                        check("load_account");

                    }
                    else if(state .equals("teacher"))
                    {
                        check("load_teacher");
                    }
                    else
                    {
                        Toast.makeText(password_change.this,"您还没有说明身份!",Toast.LENGTH_SHORT).show();
                    }
            }
        });

        //为新密码进行检查
        edit_newpassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                if(textInputLayout.getCounterMaxLength()<edit_newpassword.length())
                {
                    textInputLayout.setError("超出字数限制!");
                }
                else
                {
                    textInputLayout.setErrorEnabled(false);
                }
            }
        });
    }

    //绑定组件
    public void initView()
    {
        button_change = findViewById(R.id.button_change_password_ok);

        edit_account = findViewById(R.id.et_c_account);

        edit_oldpassword = findViewById(R.id.et_c_oldpassword);

        edit_newpassword = findViewById(R.id.et_c_newpassword);

        textInputLayout = findViewById(R.id.textinput_newpassword);

        edit_confirm = findViewById(R.id.et_c_confirm_newpassword);

        load_radiogroup= findViewById(R.id.password_radiogroup);

        db = new CommonDatabase().getSqliteObject(password_change.this,"test_db");
    }
    //检验正确性
    public  void  check(String string)
    {
        if(edit_account.getText().toString().equals("")||edit_confirm.getText().toString().equals("")||edit_newpassword.getText().toString().equals("")||edit_oldpassword.getText().toString().equals(""))
        {
            Toast.makeText(password_change.this,"不能为空!",Toast.LENGTH_SHORT).show();
        }
        else
        {
            //去找真正密码
            Cursor cursor =db.query(string,null,"account = ?",new String[]{edit_account.getText().toString()},null,null,null);
            //如果根本没这个账户
            if(cursor.getCount()==0)
            {
                Toast.makeText(password_change.this,"没有找到该账户",Toast.LENGTH_SHORT).show();
            }
            else
            {
                while (cursor.moveToNext())
                {
                    true_password = cursor.getString(cursor.getColumnIndex("password"));
                }

                //如果原密码错误
                if(!md5(edit_oldpassword.getText().toString()).equals(true_password))
                {
                    Toast.makeText(password_change.this,"原密码错误!",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    //如果用户前后输入密码不同
                    if(!edit_newpassword.getText().toString().equals(edit_confirm .getText().toString()))
                    {
                        Toast.makeText(password_change.this,"前后两次输入与验证密码错误!",Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        ContentValues values = new ContentValues();
                        values.put("password",md5(edit_newpassword.getText().toString()));
                        //更新数据库
                        db.update(string, values, "account = ? ", new String[]{edit_account.getText().toString()});

                        Toast.makeText(password_change.this,"修改成功!",Toast.LENGTH_SHORT).show();

                        startActivity(new Intent(password_change.this, load.class));
                    }
                }

            }



        }
    }
}

登录和数据库准备先到这里了。图片什么的需求可以到我的github上查看获取,大部分来源于阿里巴巴矢量图标库,小部分来源于我个人。

由于是边学安卓边做的,有些细节问题没有注意,大佬们多多指正。

发布了200 篇原创文章 · 获赞 99 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_43889841/article/details/95725806