蓝燕云
电话咨询
在线咨询
免费试用

Android小项目之学生管理系统代码怎么实现?从零开始教你开发完整功能

蓝燕云
2026-05-18
Android小项目之学生管理系统代码怎么实现?从零开始教你开发完整功能

本文详细讲解如何从零开始开发一个Android小项目——学生管理系统,涵盖数据库设计、模型类编写、DAO层实现、RecyclerView适配器开发及界面交互逻辑。文章以Java为例,逐步演示添加、查看、编辑、删除学生信息的全过程,并提供完整的代码示例和常见问题解决方案,适合初学者掌握Android开发核心技能。

Android小项目之学生管理系统代码怎么实现?从零开始教你开发完整功能

在移动开发学习过程中,一个简单但实用的小项目往往能帮助开发者快速掌握核心技能。学生管理系统是一个非常经典的入门级Android应用案例,它不仅涵盖了UI设计、数据存储、列表展示等基础功能,还能让你深入理解Activity生命周期、SQLite数据库操作、RecyclerView适配器编写等关键知识点。

一、项目目标与功能规划

我们构建的学生管理系统旨在实现以下基本功能:

  1. 添加学生信息(姓名、学号、年龄)
  2. 查看所有学生列表
  3. 编辑学生信息
  4. 删除学生记录
  5. 数据持久化存储(使用SQLite数据库)

整个系统采用MVC架构思想进行模块划分:Model负责数据处理,View负责界面展示,Controller负责逻辑控制。这样便于后期扩展和维护。

二、环境准备与项目创建

首先确保你已安装最新版本的Android Studio,并配置好JDK环境。打开Android Studio后,选择“New Project” -> “Empty Activity”,设置如下参数:

  • Application name: StudentManager
  • Package name: com.example.studentmanager
  • Language: Java or Kotlin(推荐Java初学者)
  • Minimum API Level: 21(Android 5.0)

项目创建完成后,你会看到标准的文件结构,包括MainActivity.java、activity_main.xml以及res目录下的资源文件。

三、数据库设计与实现

为了实现学生信息的持久化存储,我们将使用SQLite数据库。首先新建一个数据库帮助类StudentDBHelper,继承自SQLiteOpenHelper:

public class StudentDBHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "student.db";
    private static final int DATABASE_VERSION = 1;

    public StudentDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE = "CREATE TABLE students(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, student_id TEXT, age INTEGER);";
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS students");
        onCreate(db);
    }
}

这个类定义了数据库名称、版本号,并在onCreate方法中创建了一个名为students的表,包含id、name、student_id和age四个字段。

四、模型类设计

接下来创建一个Student实体类,用于封装学生信息:

public class Student {
    private int id;
    private String name;
    private String studentId;
    private int age;

    public Student(String name, String studentId, int age) {
        this.name = name;
        this.studentId = studentId;
        this.age = age;
    }

    // Getters and Setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getStudentId() { return studentId; }
    public void setStudentId(String studentId) { this.studentId = studentId; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

五、DAO层实现(数据访问对象)

DAO层负责与数据库交互,提供增删改查方法。新建StudentDAO类:

public class StudentDAO {
    private SQLiteDatabase db;
    private StudentDBHelper dbHelper;

    public StudentDAO(Context context) {
        dbHelper = new StudentDBHelper(context);
    }

    public void open() {
        db = dbHelper.getWritableDatabase();
    }

    public void close() {
        if (db != null) db.close();
    }

    public long addStudent(Student student) {
        ContentValues values = new ContentValues();
        values.put("name", student.getName());
        values.put("student_id", student.getStudentId());
        values.put("age", student.getAge());
        return db.insert("students", null, values);
    }

    public List getAllStudents() {
        List students = new ArrayList<>();
        Cursor cursor = db.query("students", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                Student s = new Student(
                    cursor.getString(cursor.getColumnIndexOrThrow("name")),
                    cursor.getString(cursor.getColumnIndexOrThrow("student_id")),
                    cursor.getInt(cursor.getColumnIndexOrThrow("age"))
                );
                s.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
                students.add(s);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return students;
    }

    public boolean updateStudent(Student student) {
        ContentValues values = new ContentValues();
        values.put("name", student.getName());
        values.put("student_id", student.getStudentId());
        values.put("age", student.getAge());
        return db.update("students", values, "id=?", new String[]{String.valueOf(student.getId())}) > 0;
    }

    public boolean deleteStudent(int id) {
        return db.delete("students", "id=?", new String[]{String.valueOf(id)}) > 0;
    }
}

六、主界面布局与功能实现

在activity_main.xml中添加一个按钮用于跳转到添加页面,以及一个RecyclerView用于显示学生列表:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="添加学生" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

MainActivity中初始化控件并绑定数据源:

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private StudentAdapter adapter;
    private StudentDAO dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerView);
        Button btnAdd = findViewById(R.id.btnAdd);

        dao = new StudentDAO(this);
        dao.open();

        adapter = new StudentAdapter(this, dao.getAllStudents());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        btnAdd.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, AddStudentActivity.class);
            startActivity(intent);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.refresh(dao.getAllStudents());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dao.close();
    }
}

七、适配器与列表项视图

创建StudentAdapter来管理RecyclerView的数据绑定:

public class StudentAdapter extends RecyclerView.Adapter {
    private Context context;
    private List students;

    public StudentAdapter(Context context, List students) {
        this.context = context;
        this.students = students;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_student, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Student student = students.get(position);
        holder.tvName.setText(student.getName());
        holder.tvId.setText(student.getStudentId());
        holder.tvAge.setText(String.valueOf(student.getAge()));

        holder.itemView.setOnLongClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("确认删除")
                   .setMessage("是否删除该学生?")
                   .setPositiveButton("是", (dialog, which) -> {
                       StudentDAO dao = new StudentDAO(context);
                       dao.open();
                       dao.deleteStudent(student.getId());
                       dao.close();
                       refresh(students);
                   })
                   .setNegativeButton("否", null)
                   .show();
            return true;
        });
    }

    @Override
    public int getItemCount() {
        return students.size();
    }

    public void refresh(List newStudents) {
        this.students.clear();
        this.students.addAll(newStudents);
        notifyDataSetChanged();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvName, tvId, tvAge;

        public ViewHolder(View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvName);
            tvId = itemView.findViewById(R.id.tvId);
            tvAge = itemView.findViewById(R.id.tvAge);
        }
    }
}

对应的item_student.xml布局文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="8dp"
    android:background="?android:attr/selectableItemBackground">

    <TextView
        android:id="@+id/tvName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tvId"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/tvAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp" />

</LinearLayout>

八、添加学生的功能实现

新建AddStudentActivity,提供表单让用户输入学生信息:

public class AddStudentActivity extends AppCompatActivity {
    private EditText etName, etId, etAge;
    private StudentDAO dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_student);

        etName = findViewById(R.id.etName);
        etId = findViewById(R.id.etId);
        etAge = findViewById(R.id.etAge);

        dao = new StudentDAO(this);
        dao.open();

        findViewById(R.id.btnSave).setOnClickListener(v -> {
            String name = etName.getText().toString().trim();
            String id = etId.getText().toString().trim();
            String ageStr = etAge.getText().toString().trim();

            if (name.isEmpty() || id.isEmpty() || ageStr.isEmpty()) {
                Toast.makeText(this, "请输入完整信息", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                int age = Integer.parseInt(ageStr);
                Student student = new Student(name, id, age);
                dao.addStudent(student);
                finish();
            } catch (NumberFormatException e) {
                Toast.makeText(this, "年龄必须为数字", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dao.close();
    }
}

activity_add_student.xml布局如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="姓名" />

    <EditText
        android:id="@+id/etId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="学号" />

    <EditText
        android:id="@+id/etAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="年龄"
        android:inputType="number" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存" />

</LinearLayout>

九、常见问题与优化建议

在实际开发中可能会遇到以下问题:

  • 内存泄漏风险:务必在Activity销毁时关闭数据库连接,避免长时间持有Context导致内存泄漏。
  • 线程安全:虽然本项目未涉及网络请求,但在复杂场景下应将数据库操作放在子线程中执行。
  • 用户体验提升:可以增加加载动画、Toast提示、错误边界处理等细节优化。
  • 代码复用:未来可考虑将DAO封装成通用组件,支持多种数据模型。

十、总结与进阶方向

通过本项目的实践,你已经掌握了Android开发中最基础但也最重要的几个知识点:SQLite数据库操作、RecyclerView使用、Activity生命周期管理、数据绑定机制等。这不仅是学习Android的第一步,也是通往更复杂应用开发的跳板。

下一步你可以尝试:

  • 加入用户登录验证功能
  • 使用Room替代原生SQLite(更现代化的ORM框架)
  • 集成SharedPreferences保存用户偏好设置
  • 添加搜索过滤功能,提高查询效率
  • 打包发布到Google Play或华为应用市场

记住:每一个大项目都是从小项目积累起来的。坚持动手实践,才能真正成长为一名合格的Android开发者!

用户关注问题

Q1

什么叫工程管理系统?

工程管理系统是一种专为工程项目设计的管理软件,它集成了项目计划、进度跟踪、成本控制、资源管理、质量监管等多个功能模块。 简单来说,就像是一个数字化的工程项目管家,能够帮你全面、高效地管理整个工程项目。

Q2

工程管理系统具体是做什么的?

工程管理系统可以帮助你制定详细的项目计划,明确各阶段的任务和时间节点;还能实时监控项目进度, 一旦发现有延误的风险,就能立即采取措施进行调整。同时,它还能帮你有效控制成本,避免不必要的浪费。

Q3

企业为什么需要引入工程管理系统?

随着工程项目规模的不断扩大和复杂性的增加,传统的人工管理方式已经难以满足需求。 而工程管理系统能够帮助企业实现工程项目的数字化、信息化管理,提高管理效率和准确性, 有效避免延误和浪费。

Q4

工程管理系统有哪些优势?

工程管理系统的优势主要体现在提高管理效率、增强决策准确性、降低成本风险、提升项目质量等方面。 通过自动化和智能化的管理手段,减少人工干预和重复劳动,帮助企业更好地把握项目进展和趋势。