在Androidstudio中设计一个简单学生选课系统并给出代码
时间: 2024-06-07 08:12:05 浏览: 210
为了设计一个简单的学生选课系统,我们需要考虑以下几个方面:
1. 数据存储:我们需要在系统中存储学生和课程的信息,可以使用SQLite数据库进行存储。
2. 用户界面:我们需要提供一个界面来展示课程信息和学生信息,以及提供选课和退课的功能。
3. 业务逻辑:我们需要编写代码实现选课和退课的逻辑,以及显示课程和学生的信息。
下面是一个简单的学生选课系统的示例代码:
1. 首先,在Android Studio中创建一个新的项目,并添加SQLite库的依赖。
2. 创建一个名为Course的Java类,表示课程信息:
```java
public class Course {
private int id;
private String name;
private int capacity;
public Course(int id, String name, int capacity) {
this.id = id;
this.name = name;
this.capacity = capacity;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
}
```
3. 创建一个名为Student的Java类,表示学生信息:
```java
public class Student {
private int id;
private String name;
private List<Course> courses;
public Student(int id, String name) {
this.id = id;
this.name = name;
this.courses = new ArrayList<>();
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public List<Course> getCourses() {
return courses;
}
public void addCourse(Course course) {
courses.add(course);
}
public void removeCourse(Course course) {
courses.remove(course);
}
}
```
4. 创建一个名为DatabaseHelper的类,用于创建和管理SQLite数据库:
```java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "courses.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_COURSES = "courses";
private static final String TABLE_STUDENTS = "students";
private static final String TABLE_SELECTIONS = "selections";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_CAPACITY = "capacity";
private static final String COLUMN_STUDENT_ID = "student_id";
private static final String COLUMN_COURSE_ID = "course_id";
private static final String CREATE_TABLE_COURSES = "CREATE TABLE " + TABLE_COURSES +
"(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " TEXT," +
COLUMN_CAPACITY + " INTEGER)";
private static final String CREATE_TABLE_STUDENTS = "CREATE TABLE " + TABLE_STUDENTS +
"(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " TEXT)";
private static final String CREATE_TABLE_SELECTIONS = "CREATE TABLE " + TABLE_SELECTIONS +
"(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_STUDENT_ID + " INTEGER," +
COLUMN_COURSE_ID + " INTEGER," +
"FOREIGN KEY(" + COLUMN_STUDENT_ID + ") REFERENCES " + TABLE_STUDENTS + "(" + COLUMN_ID + ")," +
"FOREIGN KEY(" + COLUMN_COURSE_ID + ") REFERENCES " + TABLE_COURSES + "(" + COLUMN_ID + "))";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_COURSES);
db.execSQL(CREATE_TABLE_STUDENTS);
db.execSQL(CREATE_TABLE_SELECTIONS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SELECTIONS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENTS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COURSES);
onCreate(db);
}
}
```
5. 创建一个名为MainActivity的类,用于实现界面和选课逻辑:
```java
public class MainActivity extends AppCompatActivity {
private DatabaseHelper dbHelper;
private ListView courseListView;
private ListView studentListView;
private List<Course> courseList;
private List<Student> studentList;
private CourseAdapter courseAdapter;
private StudentAdapter studentAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DatabaseHelper(this);
courseListView = findViewById(R.id.course_list_view);
studentListView = findViewById(R.id.student_list_view);
courseList = new ArrayList<>();
studentList = new ArrayList<>();
courseAdapter = new CourseAdapter(this, courseList);
studentAdapter = new StudentAdapter(this, studentList);
courseListView.setAdapter(courseAdapter);
studentListView.setAdapter(studentAdapter);
updateData();
courseListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Course course = courseList.get(position);
showCourseDialog(course);
}
});
studentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Student student = studentList.get(position);
showStudentDialog(student);
}
});
}
private void showCourseDialog(final Course course) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(course.getName());
View view = LayoutInflater.from(this).inflate(R.layout.dialog_course, null);
TextView capacityTextView = view.findViewById(R.id.capacity_text_view);
final EditText capacityEditText = view.findViewById(R.id.capacity_edit_text);
capacityTextView.setText("Capacity: " + course.getCapacity());
capacityEditText.setText(String.valueOf(course.getCapacity()));
builder.setView(view);
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int capacity = Integer.parseInt(capacityEditText.getText().toString());
course.setCapacity(capacity);
updateCourse(course);
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
private void showStudentDialog(final Student student) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(student.getName());
View view = LayoutInflater.from(this).inflate(R.layout.dialog_student, null);
final ListView courseListView = view.findViewById(R.id.course_list_view);
List<Course> availableCourses = getAvailableCourses(student);
CourseAdapter adapter = new CourseAdapter(this, availableCourses);
courseListView.setAdapter(adapter);
builder.setView(view);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int position = courseListView.getCheckedItemPosition();
if (position != ListView.INVALID_POSITION) {
Course course = (Course) courseListView.getItemAtPosition(position);
addCourse(student, course);
}
}
});
builder.setNegativeButton("Remove", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
List<Course> selectedCourses = getSelectedCourses(student);
Course[] courses = new Course[selectedCourses.size()];
boolean[] checkedItems = new boolean[selectedCourses.size()];
for (int i = 0; i < selectedCourses.size(); i++) {
courses[i] = selectedCourses.get(i);
checkedItems[i] = false;
}
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Remove Courses");
builder.setMultiChoiceItems(courses, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkedItems[which] = isChecked;
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < checkedItems.length; i++) {
if (checkedItems[i]) {
Course course = courses[i];
removeCourse(student, course);
}
}
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
});
builder.show();
}
private void updateData() {
courseList.clear();
studentList.clear();
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_COURSES, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME));
int capacity = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_CAPACITY));
Course course = new Course(id, name, capacity);
courseList.add(course);
}
cursor.close();
cursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_STUDENTS, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME));
Student student = new Student(id, name);
studentList.add(student);
}
cursor.close();
for (Student student : studentList) {
cursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_SELECTIONS +
" WHERE " + DatabaseHelper.COLUMN_STUDENT_ID + " = ?", new String[]{String.valueOf(student.getId())});
while (cursor.moveToNext()) {
int courseId = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_COURSE_ID));
for (Course course : courseList) {
if (course.getId() == courseId) {
student.addCourse(course);
break;
}
}
}
cursor.close();
}
courseAdapter.notifyDataSetChanged();
studentAdapter.notifyDataSetChanged();
}
private void updateCourse(Course course) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_NAME, course.getName());
values.put(DatabaseHelper.COLUMN_CAPACITY, course.getCapacity());
db.update(DatabaseHelper.TABLE_COURSES, values, DatabaseHelper.COLUMN_ID + " = ?",
new String[]{String.valueOf(course.getId())});
updateData();
}
private List<Course> getAvailableCourses(Student student) {
List<Course> availableCourses = new ArrayList<>();
for (Course course : courseList) {
if (!student.getCourses().contains(course) && course.getCapacity() > 0) {
availableCourses.add(course);
}
}
return availableCourses;
}
private List<Course> getSelectedCourses(Student student) {
List<Course> selectedCourses = new ArrayList<>();
for (Course course : courseList) {
if (student.getCourses().contains(course)) {
selectedCourses.add(course);
}
}
return selectedCourses;
}
private void addCourse(Student student, Course course) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_STUDENT_ID, student.getId());
values.put(DatabaseHelper.COLUMN_COURSE_ID, course.getId());
db.insert(DatabaseHelper.TABLE_SELECTIONS, null, values);
updateData();
}
private void removeCourse(Student student, Course course) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(DatabaseHelper.TABLE_SELECTIONS,
DatabaseHelper.COLUMN_STUDENT_ID + " = ? AND " + DatabaseHelper.COLUMN_COURSE_ID + " = ?",
new String[]{String.valueOf(student.getId()), String.valueOf(course.getId())});
updateData();
}
private static class CourseAdapter extends ArrayAdapter<Course> {
public CourseAdapter(Context context, List<Course> courses) {
super(context, 0, courses);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
}
Course course = getItem(position);
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(course.getName());
return convertView;
}
}
private static class StudentAdapter extends ArrayAdapter<Student> {
public StudentAdapter(Context context, List<Student> students) {
super(context, 0, students);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
}
Student student = getItem(position);
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(student.getName());
return convertView;
}
}
}
```
6. 最后,在布局文件中添加ListView和对话框的布局:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/course_list_view"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<ListView
android:id="@+id/student_list_view"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
```
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/capacity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/capacity_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
```
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="@+id/course_list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="single"/>
</LinearLayout>
```
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="@+id/course_list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="multiple"/>
</LinearLayout>
```
这样,一个简单的学生选课系统就完成了。
阅读全文