在我的应用中,我使用活动添加新课程并将其保存在SQLite数据库中。但是当我尝试访问其他活动中添加的课程以在Spinner中显示它们时,该表似乎是空的。
这是我保存课程的代码(第一项活动):
SQLiteHelperCourse courseDbHelper = new SQLiteHelperCourse(this);
SQLiteDatabase dbw = courseDbHelper.getWritableDatabase();
String courseNameString, yearString, semesterString, creditsString;
AlertCourseError courseAlert = new AlertCourseError();
if(v.getId() == R.id.btnSaveCourse)
{
if(!etCourseName.getText().toString().matches("") || !etCredits.getText().toString().matches(""))
{
courseNameString = etCourseName.getText().toString();
yearString = yearSpinner.getSelectedItem().toString();
semesterString = semesterSpinner.getSelectedItem().toString();
creditsString = etCredits.getText().toString();
ContentValues values = new ContentValues();
values.put(CourseEntry.COLUMN_NAME_COURSE_NAME, courseNameString);
values.put(CourseEntry.COLUMN_NAME_YEAR, yearString);
values.put(CourseEntry.COLUMN_NAME_SEMESTER, semesterString);
values.put(CourseEntry.COLUMN_NAME_CREDITS, creditsString);
dbw.insert(CourseEntry.TABLE_NAME, CourseEntry.COLUMN_NAME_NULLABLE, values);
}
}
这是在Spinner中显示已保存课程的代码(第二项活动)
SQLiteDatabase dbr = courseDbHelper.getReadableDatabase();
String[] projection = { CourseEntry.COLUMN_NAME_COURSE_NAME };
final ArrayList<String> list = new ArrayList<String>();
Cursor curs = dbr.query(CourseEntry.TABLE_NAME, projection, null, null,
null, null, null);
curs.moveToFirst();
while (curs.moveToNext()) {
list.add(curs.getString(curs.getColumnIndexOrThrow(CourseEntry.COLUMN_NAME_COURSE_NAME)));
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_spinner_item, list);
courseSpinner.setAdapter(adapter);
答案 0 :(得分:0)
SQLiteHelper类实例必须是同一个名称。在上面的代码中,一个是:
SQLiteDatabase dbw = courseDbHelper.getWritableDatabase();
另一个是:
SQLiteDatabase dbr = courseDbHelper.getReadableDatabase();
将它们更改为:SQLiteDatabase dbw = courseDbHelper.getWritableDatabase();
现在它完美无缺。