古之立大事者,不惟有超世之才,亦必有坚忍不拔之志。——苏轼
---------------🍎------------🍉--------------
🐼学编程的bird的博客,邀您一起学习🦌
----------------🥕------------🥭-------------😊很高兴你打开了这篇博客。
★如有疑问不解或者说有想问的地方,都可以在下方评论留言,博主看到会尽快回复的。
★当然,期待你的点赞+关注哦!★本人微信:wxid_v28nw5cckzz622,若需要帮助,请备注来源+意图
————————————————
版权声明:本文为CSDN博主「学编程的bird」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:Android Studio 大作业--学生信息管理系统-CSDN博客https://blog.csdn.net/m0_64069699/article/details/135324803
简易学生信息管理系统项目需求,大致需要以下Java文件和XML布局文件: Java文件: Student 类(实体类):用于存储学生信息。 StudentDBHelper 类(数据库操作类):继承自SQLiteOpenHelper,负责创建表、插入、删除、更新和查询学生数据。 StudentListAdapter 类(RecyclerView Adapter):适配器类,用于在“学生列表”模块展示学生数据。 StudentListFragment 类(Fragment):实现学生列表界面功能,包含RecyclerView及其Adapter的初始化等。 AddStudentFragment 类(Fragment):实现添加学生界面功能,包含EditText输入框、Button提交按钮、ImageView头像选择等。 SearchStudentFragment 类(Fragment):实现查询学生界面功能,包含EditText输入框、CheckBox或RadioButton查询条件选择、查询结果展示列表的初始化等。 SearchStudentListAdapter 类(RecyclerView Adapter):适配器类,用于在“搜索”模块展示学生数据。 MainActivity:用于初始化底部导航栏与ViewPager2,并管理各个Fragment。 XML布局文件: activity_main.xml:主Activity布局文件,包含ViewPager2和TabLayout等控件。 fragment_student_list.xml:学生列表Fragment的布局文件,包含RecyclerView等控件。 fragment_add_student.xml:添加学生Fragment的布局文件,包含姓名、学号、专业等EditText输入框以及上传或选择图片的ImageView和提交按钮等控件。 item_student1.xml:RecyclerView中单个学生项的布局文件,包含显示学生信息的各种TextView、ImageView等控件。 fragment_search_student.xml:查询学生Fragment的布局文件,包含查询输入框、查询条件选择控件以及查询结果展示的ListView或RecyclerView控件。 item_student2.xml:RecyclerView中单个学生项的布局文件,包含显示学生信息的各种TextView、ImageView等控件。 dialog_delete_confirm.xml:删除确认AlertDialog或PopupWindow的布局文件,包含提示文字和确认/取消按钮。 bottom_navigation_menu.xml:底部导航栏。
此APP中包含以下控件: Button、TextView、EditText、ImageView、Toast、Activity 跳转和传值、ViewPager2+Fragment 底部导航 PopupWindow & AlertDialog、数据库 RadioButton、CheckBox、返回值、RecyclerView
package com.example.myfinalwork; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.viewpager2.widget.ViewPager2; import androidx.viewpager2.adapter.FragmentStateAdapter; import androidx.appcompat.widget.Toolbar; import android.os.Bundle; import android.view.MenuItem; import android.view.Menu; import android.widget.Toast; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.example.myfinalwork.StudentListRefreshListener; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements StudentListRefreshListener { private ViewPager2 viewPager; private BottomNavigationView bottomNavigationView; private ListfragmentsList; private MenuItem lastSelectedMenuItem; private StudentListFragment studentListFragment; // 新增变量 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化ViewPager2和BottomNavigationView viewPager = findViewById(R.id.view_pager); setupViewPager(); // 在这里找到并保存StudentListFragment的引用 for (Fragment fragment : fragmentsList) { if (fragment instanceof StudentListFragment) { studentListFragment = (StudentListFragment) fragment; break; } } bottomNavigationView = findViewById(R.id.bottom_navigation_view); bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener()); bottomNavigationView.setSelectedItemId(R.id.action_student_list); } @Override public void onStudentListRefresh() { if (studentListFragment != null) { studentListFragment.refreshStudentList(); } } private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener() { return new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.action_student_list) { viewPager.setCurrentItem(0); } else if (item.getItemId() == R.id.action_add_student) { viewPager.setCurrentItem(1); } else if (item.getItemId() == R.id.action_search_student) { viewPager.setCurrentItem(2); } lastSelectedMenuItem = item; return true; } }; } private void setupViewPager() { fragmentsList = new ArrayList<>(); studentListFragment = new StudentListFragment(); // 修改:直接使用类级别的变量 AddStudentFragment addStudentFragment = new AddStudentFragment(); SearchStudentFragment searchStudentFragment = new SearchStudentFragment(); // 为AddStudentFragment设置一个接口回调以通知MainActivity刷新列表 addStudentFragment.setStudentListRefreshListener(this); fragmentsList.add(studentListFragment); fragmentsList.add(addStudentFragment); fragmentsList.add(searchStudentFragment); viewPager.setAdapter(new FragmentStateAdapter(this) { @NonNull @Override public Fragment createFragment(int position) { return fragmentsList.get(position); } @Override public int getItemCount() { return fragmentsList.size(); } }); viewPager.setUserInputEnabled(false); // 可选:禁用手动滑动切换页面 } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.bottom_navigation_menu, menu); return true; } }
package com.example.myfinalwork; public class Student { private String id; private String name; private String major; private boolean selected; // 添加一个布尔变量来表示学生是否被选中 public Student(String id, String name, String major) { this.id = id; this.name = name; this.major = major; this.selected = false; // 初始化时默认未选中 } public Student() { } // Getters and Setters public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } // 新增isSelected()和setSelected()方法 public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } @Override public String toString() { return "Student{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", major='" + major + '\'' + ", selected=" + selected + '}'; } }
package com.example.myfinalwork; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; public class StudentDBHelper extends SQLiteOpenHelper { // 数据库名称 private static final String DATABASE_NAME = "StudentManager.db"; // 数据库版本号,每次更新数据库结构时需要增加 private static final int DATABASE_VERSION = 1; // 学生信息表名 public static final String TABLE_NAME_STUDENTS = "students"; // 表列名定义 public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_MAJOR = "major"; // 创建学生信息表的SQL语句 private static final String CREATE_TABLE_STUDENTS = "CREATE TABLE " + TABLE_NAME_STUDENTS + "(" + COLUMN_ID + " TEXT PRIMARY KEY," + COLUMN_NAME + " TEXT NOT NULL," + COLUMN_MAJOR + " TEXT NOT NULL" + ")"; public StudentDBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_STUDENTS); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 在数据库版本升级时,可以在此处添加数据迁移逻辑或者删除旧表重建新表 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_STUDENTS); onCreate(db); } /** * 一个简单的方法用于将学生信息插入数据库,具体实现由StudentDBHelper提供 * @param student 要插入的学生对象 */ public void insertStudent(Student student) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_ID, student.getId()); values.put(COLUMN_NAME, student.getName()); values.put(COLUMN_MAJOR, student.getMajor()); db.insert(TABLE_NAME_STUDENTS, null, values); db.close(); // 关闭数据库连接 } /** * 根据查询条件搜索学生 * @param query 搜索关键词 * @param searchBy 搜索依据字段("name" 或 "id" 或 "major") * @return 匹配到的学生列表 */ public ListsearchStudents(String query, String searchBy) { List studentList = new ArrayList<>(); SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor; if (searchBy.equals("name")) { cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME_STUDENTS + " WHERE " + COLUMN_NAME + " LIKE ?", new String[]{"%" + query + "%"}); } else if (searchBy.equals("id")) { cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME_STUDENTS + " WHERE " + COLUMN_ID + " LIKE ?", new String[]{"%" + query + "%"}); } else if (searchBy.equals("major")) { cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME_STUDENTS + " WHERE " + COLUMN_MAJOR + " LIKE ?", new String[]{"%" + query + "%"}); } else { throw new IllegalArgumentException("Invalid searchBy field"); } if (cursor.moveToFirst()) { do { Student student = new Student(); int idColumnIndex = cursor.getColumnIndex(COLUMN_ID); int nameColumnIndex = cursor.getColumnIndex(COLUMN_NAME); int majorColumnIndex = cursor.getColumnIndex(COLUMN_MAJOR); if (idColumnIndex >= 0) { student.setId(cursor.getString(idColumnIndex)); } if (nameColumnIndex >= 0) { student.setName(cursor.getString(nameColumnIndex)); } if (majorColumnIndex >= 0) { student.setMajor(cursor.getString(majorColumnIndex)); } // 只有当所有必要的字段都获取成功时才添加到列表 if (student.getId() != null && student.getName() != null && student.getMajor() != null) { studentList.add(student); } } while (cursor.moveToNext()); } cursor.close(); db.close(); return studentList; } /** * 获取所有学生信息 * @return 所有的学生列表 */ @SuppressLint("Range") public List getAllStudents() { List studentList = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_NAME_STUDENTS, null, null, null, null, null, null); if (cursor.moveToFirst()) { do { Student student = new Student(); student.setId(cursor.getString(cursor.getColumnIndex(COLUMN_ID))); student.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME))); student.setMajor(cursor.getString(cursor.getColumnIndex(COLUMN_MAJOR))); studentList.add(student); } while (cursor.moveToNext()); } cursor.close(); db.close(); return studentList; } /** * 根据学生ID从数据库中删除学生信息 * @param studentId 要删除的学生的ID */ public void deleteStudent(String studentId) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_NAME_STUDENTS, COLUMN_ID + "=?", new String[]{studentId}); db.close(); // 关闭数据库连接 } }
package com.example.myfinalwork; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class SearchStudentFragment extends Fragment { private EditText editTextSearchQuery; private RadioButton radioButtonByName, radioButtonById,radioButtonByMajor; private RecyclerView recyclerViewSearchResults; private SearchListAdapter searchResultsAdapter; private ListsearchedStudents; private StudentDBHelper dbHelper; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_search_student, container, false); // 初始化控件引用 editTextSearchQuery = rootView.findViewById(R.id.edit_text_search_query); radioButtonByName = rootView.findViewById(R.id.radio_button_name); radioButtonById = rootView.findViewById(R.id.radio_button_id); radioButtonByMajor = rootView.findViewById(R.id.radio_button_major); recyclerViewSearchResults = rootView.findViewById(R.id.recycler_view_search_results); recyclerViewSearchResults.setLayoutManager(new LinearLayoutManager(requireContext())); // 初始化数据库帮助类 dbHelper = new StudentDBHelper(getActivity().getApplicationContext()); // 初始化搜索结果列表的适配器 searchedStudents = new ArrayList<>(); searchResultsAdapter = new SearchListAdapter(requireContext(), searchedStudents); recyclerViewSearchResults.setAdapter(searchResultsAdapter); // 添加搜索按钮点击事件监听器 Button buttonSearch = rootView.findViewById(R.id.button_search); buttonSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String query = editTextSearchQuery.getText().toString().trim(); String searchBy; if (radioButtonByName.isChecked()) { searchBy = "name"; } else if (radioButtonById.isChecked()) { searchBy = "id"; } else if (radioButtonByMajor.isChecked()) { // 新增部分 searchBy = "major"; } else { searchBy = "name"; // 默认值,如果都没有选中则按照姓名搜索 } if (!query.isEmpty()) { searchedStudents.clear(); List students = dbHelper.searchStudents(query, searchBy); searchedStudents.addAll(students); searchResultsAdapter.notifyDataSetChanged(); if (searchedStudents.isEmpty()) { Toast.makeText(getContext(), "未找到匹配的学生", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getContext(), "请输入搜索关键词", Toast.LENGTH_SHORT).show(); } } }); return rootView; } }
package com.example.myfinalwork; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class SearchListAdapter extends RecyclerView.Adapter{ private Context context; private List studentList; public SearchListAdapter(Context context, List studentList) { this.context = context; this.studentList = studentList; } @NonNull @Override public StudentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(context).inflate(R.layout.item_student2, parent, false); return new StudentViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull StudentViewHolder holder, int position) { final Student currentStudent = studentList.get(position); holder.studentName.setText(currentStudent.getName()); holder.studentId.setText(currentStudent.getId()); holder.studentMajor.setText(currentStudent.getMajor()); } @Override public int getItemCount() { return studentList.size(); } // ViewHolder 类用于缓存视图组件 public static class StudentViewHolder extends RecyclerView.ViewHolder { TextView studentName, studentId, studentMajor; CheckBox checkBoxSelect; public StudentViewHolder(@NonNull View itemView) { super(itemView); studentName = itemView.findViewById(R.id.text_view_student_name); studentId = itemView.findViewById(R.id.text_view_student_id); studentMajor = itemView.findViewById(R.id.text_view_student_major); checkBoxSelect = itemView.findViewById(R.id.check_box_select); } } }
package com.example.myfinalwork; import android.app.AlertDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class StudentListFragment extends Fragment implements StudentListAdapter.OnItemSelectedListener { private RecyclerView recyclerView; private StudentListAdapter adapter; private ListstudentList; private Button deleteButton; private List selectedStudents = new ArrayList<>(); private StudentDBHelper dbHelper; private AlertDialog deleteConfirmationDialog; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 加载fragment布局 View rootView = inflater.inflate(R.layout.fragment_student_list, container, false); // 初始化数据库助手 dbHelper = new StudentDBHelper(requireContext()); // 初始化RecyclerView和Adapter recyclerView = rootView.findViewById(R.id.recycler_view_students); recyclerView.setLayoutManager(new LinearLayoutManager(requireContext())); // 这里可以填充或从数据库加载学生数据 // 初始化数据列表 studentList = new ArrayList<>(); studentList = dbHelper.getAllStudents(); // 创建并设置Adapter adapter = new StudentListAdapter(requireContext(), studentList); adapter.setOnItemSelectedListener(this); // 设置选择监听器 recyclerView.setAdapter(adapter); // 获取并设置删除按钮点击事件 deleteButton = rootView.findViewById(R.id.button_delete); deleteButton.setOnClickListener(v -> showDeleteConfirmationDialog()); // 获取并设置刷新按钮点击事件 Button refreshButton = rootView.findViewById(R.id.button_refresh); refreshButton.setOnClickListener(v -> { refreshStudentList(); Toast.makeText(requireContext(), "学生列表已刷新", Toast.LENGTH_SHORT).show(); }); return rootView; } // 显示删除确认对话框 private void showDeleteConfirmationDialog() { if (!selectedStudents.isEmpty()) { AlertDialog.Builder builder = new AlertDialog.Builder(requireContext()); View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_delete_confirm, null); Button btnCancel = dialogView.findViewById(R.id.button_cancel); Button btnDelete = dialogView.findViewById(R.id.button_delete); btnCancel.setOnClickListener(v -> deleteConfirmationDialog.dismiss()); btnDelete.setOnClickListener(v -> { for (Student student : selectedStudents) { dbHelper.deleteStudent(student.getId()); // 从数据库中删除学生 studentList.remove(student); // 从列表中移除学生 } selectedStudents.clear(); // 清空已删除的学生列表 adapter.notifyDataSetChanged(); // 刷新RecyclerView deleteConfirmationDialog.dismiss(); Toast.makeText(requireContext(), "删除成功", Toast.LENGTH_SHORT).show(); }); deleteConfirmationDialog = builder.setView(dialogView) .setTitle("删除确认") .create(); deleteConfirmationDialog.show(); } else { Toast.makeText(requireContext(), "请先选择要删除的学生", Toast.LENGTH_SHORT).show(); } } @Override public void onItemSelected(Student student, boolean selected) { if (selected) { selectedStudents.add(student); } else { selectedStudents.remove(student); } } public void refreshStudentList() { // 从数据库重新获取学生数据 studentList.clear(); // 清空现有数据 studentList.addAll(dbHelper.getAllStudents()); // 将新数据添加到studentList adapter.notifyDataSetChanged(); // 刷新RecyclerView的数据 } }
package com.example.myfinalwork; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class StudentListAdapter extends RecyclerView.Adapter{ private Context context; private List studentList; private OnItemSelectedListener listener; public StudentListAdapter(Context context, List studentList) { this.context = context; this.studentList = studentList; } // 添加一个接口,用于监听选择事件 public interface OnItemSelectedListener { void onItemSelected(Student student, boolean selected); } public void setOnItemSelectedListener(OnItemSelectedListener listener) { this.listener = listener; } @NonNull @Override public StudentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(context).inflate(R.layout.item_student1, parent, false); return new StudentViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull StudentViewHolder holder, int position) { final Student currentStudent = studentList.get(position); holder.studentName.setText(currentStudent.getName()); holder.studentId.setText(currentStudent.getId()); holder.studentMajor.setText(currentStudent.getMajor()); holder.checkBoxSelect.setChecked(currentStudent.isSelected()); holder.checkBoxSelect.setOnCheckedChangeListener((buttonView, isChecked) -> { if (listener != null) { currentStudent.setSelected(isChecked); listener.onItemSelected(currentStudent, isChecked); } }); } @Override public int getItemCount() { return studentList.size(); } // ViewHolder 类用于缓存视图组件 public static class StudentViewHolder extends RecyclerView.ViewHolder { TextView studentName, studentId, studentMajor; CheckBox checkBoxSelect; public StudentViewHolder(@NonNull View itemView) { super(itemView); studentName = itemView.findViewById(R.id.text_view_student_name); studentId = itemView.findViewById(R.id.text_view_student_id); studentMajor = itemView.findViewById(R.id.text_view_student_major); checkBoxSelect = itemView.findViewById(R.id.check_box_select); } } }
package com.example.myfinalwork; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import java.util.List; public class AddStudentFragment extends Fragment { private EditText editTextName, editTextId, editTextMajor; private Button buttonSubmit; private StudentDBHelper dbHelper; private StudentListRefreshListener refreshListener; // 移除MainActivity前缀,因为它是一个接口引用 public void setStudentListRefreshListener(StudentListRefreshListener listener) { this.refreshListener = listener; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_add_student, container, false); // 初始化控件引用 editTextName = rootView.findViewById(R.id.edit_text_name); editTextId = rootView.findViewById(R.id.edit_text_student_id); editTextMajor = rootView.findViewById(R.id.edit_text_major); buttonSubmit = rootView.findViewById(R.id.button_submit); // 初始化数据库帮助类 dbHelper = new StudentDBHelper(getActivity().getApplicationContext()); // 获取宿主Activity的引用并设置监听器(已在setupViewPager()中完成) // 添加提交按钮点击事件监听器 buttonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = editTextName.getText().toString().trim(); String id = editTextId.getText().toString().trim(); String major = editTextMajor.getText().toString().trim(); if (!name.isEmpty() && !id.isEmpty() && !major.isEmpty()) { Student newStudent = new Student(id, name, major); dbHelper.insertStudent(newStudent); editTextName.setText(""); editTextId.setText(""); editTextMajor.setText(""); Toast.makeText(getContext(), "学生信息已添加", Toast.LENGTH_SHORT).show(); // 添加完学生后,通知宿主Activity刷新学生列表 if (refreshListener != null) { refreshListener.onStudentListRefresh(); } } else { Toast.makeText(getContext(), "请确保所有字段都已填写", Toast.LENGTH_SHORT).show(); } } }); return rootView; } }
package com.example.myfinalwork; public interface StudentListRefreshListener { void onStudentListRefresh(); }