【发布时间】:2020-08-05 18:59:30
【问题描述】:
点击 X 学期,我希望我的应用程序加载与该特定学期相关的课程,我正在尝试使用以下代码:
public void openSemestersActivity() {
final Intent semester = new Intent(this, SemesterActivity.class);
semesterListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// This works if nothing is deleted. If something is deleted we would have to add another +1 to the position
semester.putExtra("semester", db.getSemesterNameString(position + 1));
Log.d("Semester Name", db.getSemesterNameString(position + 1));
startActivity(semester);
}
});
}
现在,我想在SemesterActivity 上加载与该特定学期相关的课程,我正在尝试使用以下代码:
// Retrieving the Extra and determining the semester we want to load
Intent myIntent = getIntent();
String semester = myIntent.getStringExtra("semester");
// Creating the Database and loading the ListView
db = new DataBaseHelperC(this);
myCourses.addAll(db.getAllCoursesForThisSemester(semester));
customCourseAdapter = new CourseAdapter(getApplicationContext(), R.layout.course_row, myCourses);
courseListView.setAdapter(customCourseAdapter);
customCourseAdapter.notifyDataSetChanged();
这是位于我的DatabaseHelper 班级的方法,它应该获取该特定学期的所有课程:
public List<Course> getAllCoursesForThisSemester(String semester) {
List<Course> courses = new ArrayList<>();
// Select all query
String selectQuery = "SELECT * FROM " + Course.TABLE_NAME + " ORDER BY " + Course.COLUMN_ID + " ASC";
SQLiteDatabase db = this.getWritableDatabase();
@SuppressLint("Recycle") Cursor cursor = db.rawQuery(selectQuery, null);
// Looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Course course = new Course();
course.setNameOfCourse(cursor.getString(cursor.getColumnIndex(Course.COLUMN_COURSE)));
course.setCodeOfCourse(cursor.getString(cursor.getColumnIndex(Course.COLUMN_COURSECODE)));
course.setCreditsOfCourse(cursor.getString(cursor.getColumnIndex(Course.COLUMN_COURSECREDITS)));
course.setNameOfBackground(cursor.getString(cursor.getColumnIndex(Course.COLUMN_BACKGROUND)));
course.setId(cursor.getInt(cursor.getColumnIndex(Course.COLUMN_ID)));
courses.add(course);
}
while (cursor.moveToNext());
}
// Close db connection
db.close();
return courses;
}
我将String semester 作为参数传递,但无法弄清楚如何实际使用此参数来仅获取该特定学期的课程。这是我第一次使用数据库,值得注意的是我很难使用它并且还没有掌握它,所以任何帮助都会非常感激,因为我一直被困在这里现在大约 2 周。
现在,通过使用我目前拥有的代码,如果我在X学期添加一门课程,然后打开Y学期,则在上添加的课程X 学期也加载到 Y 学期。这就是我试图用接收String semester 作为参数的方法来解决的问题。
【问题讨论】:
-
您可以添加
Course架构吗?我想看看Course和semester是如何具体相关的。添加架构会有所帮助。 -
架构是什么意思? @ShababbKarim
-
Course的表结构是什么,换句话说,我正在寻找您在实现SQLiteOpenHelper时使用的CREATE查询
标签: java android sqlite android-sqlite