【发布时间】:2021-06-22 15:27:15
【问题描述】:
我的应用中有一个 ListView,我想在将新对象添加到数据库时对其进行更新。我查看了几个 StackOverflow 答案,但没有任何运气。这是我的 ListView 布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/course_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:textAppearance="@style/TextAppearance.AppCompat.Body2"
android:textColor="@color/black" />
<TextView
android:id="@+id/course_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:textAppearance="@style/TextAppearance.AppCompat.Body2"
android:textColor="@color/black" />
<TextView
android:id="@+id/course_credits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:textAppearance="@style/TextAppearance.AppCompat.Body2"
android:textColor="@color/black" />
</LinearLayout>
这是我的自定义适配器类:
public class CourseAdapter extends BaseAdapter {
private ArrayList<Course> courses;
private Context context;
public CourseAdapter(Context context, ArrayList<Course> courses){
this.context = context;
this.courses = courses;
}
@Override
public int getCount() {
return courses.size();
}
@Override
public Object getItem(int position) {
return courses.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater= (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.courses_listview, null);
TextView t1 = (TextView)convertView.findViewById(R.id.course_name);
TextView t2 = (TextView)convertView.findViewById(R.id.course_id);
TextView t3 = (TextView)convertView.findViewById(R.id.course_credits);
Course course = courses.get(position);
t1.setText(course.getCourseName());
t2.setText(course.getCourseId());
t3.setText(Double.toString(course.getCredits()));
return convertView;
}
public void updateList(ArrayList<Course> newCourses) {
courses.clear();
courses.addAll(newCourses);
System.out.println(newCourses.size());
this.notifyDataSetChanged();
}
}
课程类:
public class Course implements Serializable {
private String courseName, courseId, teacher, location;
private double credits;
public Course(){
}
public Course(String courseName, String courseID, double credits, String teacher, String location){
this.courseName = courseName;
this.courseId = courseID;
this.credits = credits;
this.teacher = teacher;
this.location = location;
}
public String getCourseName(){
return courseName;
}
public String getCourseId(){
return courseId;
}
public double getCredits(){
return credits;
}
}
这些是列表视图的支柱。现在是 CoursesActivity 类:
public class CoursesActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private static final int LAUNCH_ADD_COURSE = 1;
private Dialog addSemesterDialog;
private ArrayList<Semester> semesters;
private ArrayList<Course> listViewArrayList;
private ListView listView;
private Spinner spinner;
private AppBarConfiguration mAppBarConfiguration;
private CourseAdapter adapter;
private DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_courses);
LayoutInflater inflater = getLayoutInflater();
listView = (ListView)findViewById(R.id.course_list);
View convertView = (View) inflater.inflate(R.layout.content_courses, null);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
launchCourseAdd();
}
});
Semester semester = semesters.get(spinner.getSelectedItemPosition());
databaseHelper = new DatabaseHelper(this);
listViewArrayList = databaseHelper.getCourses(semester.getName());
adapter = new CourseAdapter(this, listViewArrayList);
listView.setAdapter(adapter);
}
public void launchCourseAdd(){
Intent intent = new Intent(this, AddCourseActivity.class);
intent.putExtra("semester", semesters.get(spinner.getSelectedItemPosition()));
startActivityForResult(intent, LAUNCH_ADD_COURSE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LAUNCH_ADD_COURSE) {
if(resultCode == Activity.RESULT_OK){
Semester semester = semesters.get(spinner.getSelectedItemPosition());
adapter.updateList(semester.getCourses());
}
}
}
}
这是 DatabaseHelper 类:
package com.example.finalproject.ui;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import androidx.annotation.RequiresApi;
import com.example.finalproject.Course;
import com.example.finalproject.Semester;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "gradeTrackerDB";
private static final String TABLE_SEMESTERS = "semesters";
private static final String SEMESTER_NAME = "SEMESTER_NAME";
private static final String SEMESTER_START = "SEMESTER_START_DATE";
private static final String SEMESTER_END = "SEMESTER_END_DATE";
private static final String CURRENT_SEMESTER = "CURRENT_SEMESTER";
private static final String TABLE_COURSES = "courses";
private static final String COURSE_NAME = "COURSE_NAME";
private static final String COURSE_ID = "COURSE_ID";
private static final String COURSE_CREDITS = "COURSE_CREDITS";
private static final String COURSE_COLOR = "COURSE_COLOR";
private static final String INSTRUCTOR_NAME = "INSTRUCTOR_NAME";
private static final String LOCATION = "LOCATION";
private static final String SEMESTER = "SEMESTER";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_SEMESTERS_TABLE = "CREATE TABLE " + TABLE_SEMESTERS +
"(" +
SEMESTER_NAME + " TEXT PRIMARY KEY," +
SEMESTER_START + " TEXT," +
SEMESTER_END + " TEXT," +
CURRENT_SEMESTER + " INTEGER" +
")";
String CREATE_COURSES_TABLE = "CREATE TABLE " + TABLE_COURSES +
"(" +
COURSE_ID + " TEXT," +
COURSE_NAME + " TEXT," +
COURSE_CREDITS + " REAL NOT NULL," +
COURSE_COLOR + " TEXT NOT NULL," +
SEMESTER + " TEXT NOT NULL," +
INSTRUCTOR_NAME + " TEXT," +
LOCATION + " TEXT," +
" FOREIGN KEY ("+SEMESTER+") REFERENCES "+TABLE_SEMESTERS+" ("+SEMESTER_NAME+"), " +
"PRIMARY KEY (" + COURSE_ID + ", " + COURSE_NAME + "))";
db.execSQL(CREATE_SEMESTERS_TABLE);
db.execSQL(CREATE_COURSES_TABLE);
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();
int year = localDate.getYear();
String semName="";
String startDate;
String endDate;
if (month >= 1 && month <= 4) {
semName = semName.concat("Winter ");
startDate="01/07/"+Integer.toString(year);
endDate="04/09/"+Integer.toString(year);
}
else if (month >= 5 && month <= 8) {
semName = semName.concat("Summer ");
startDate = "05/10/" + Integer.toString(year);
endDate = "08/11/" + Integer.toString(year);
}
else {
semName = semName.concat("Fall ");
startDate = "09/09/" + Integer.toString(year);
endDate = "12/08/" + Integer.toString(year);
}
semName = semName.concat(Integer.toString(year));
db.beginTransaction();
try {
// The user might already exist in the database (i.e. the same user created multiple posts).
ContentValues values = new ContentValues();
values.put(SEMESTER_NAME, semName);
values.put(SEMESTER_START, startDate);
values.put(SEMESTER_END, endDate);
values.put(CURRENT_SEMESTER, 1);
// Notice how we haven't specified the primary key. SQLite auto increments the primary key column.
db.insertOrThrow(TABLE_SEMESTERS, null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
} finally {
db.endTransaction();
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS semesters");
onCreate(db);
}
public Semester addSemester(String name, String startDate, String endDate){
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
// The user might already exist in the database (i.e. the same user created multiple posts).
ContentValues values = new ContentValues();
values.put(SEMESTER_NAME, name);
values.put(SEMESTER_START, startDate);
values.put(SEMESTER_END, endDate);
Date date1 = new SimpleDateFormat("MM/dd/yyyy").parse(startDate);
Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse(endDate);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date currentDate = new Date();
if (date1.compareTo(currentDate) <= 0 && date2.compareTo(currentDate) >= 0)
values.put(CURRENT_SEMESTER, 1);
else
values.put(CURRENT_SEMESTER, 0);
// Notice how we haven't specified the primary key. SQLite auto increments the primary key column.
db.insertOrThrow(TABLE_SEMESTERS, null, values);
db.setTransactionSuccessful();
Semester s = new Semester(name, startDate, endDate, 1);
return s;
} catch (Exception e) {
return null;
} finally {
db.endTransaction();
}
}
public ArrayList<Semester> getSemesters(){
ArrayList<Semester> semesters = new ArrayList<>();
String sql = "select * from semesters";
SQLiteDatabase db = getReadableDatabase();
Cursor c1 = db.rawQuery(sql, null);
try{
while (c1.moveToNext()){
String semesterName = c1.getString(c1.getColumnIndex(SEMESTER_NAME));
String semesterStart = c1.getString(c1.getColumnIndex(SEMESTER_START));
String semesterEnd = c1.getString(c1.getColumnIndex(SEMESTER_END));
int currentSemester = c1.getInt(c1.getColumnIndex(CURRENT_SEMESTER));
Semester semester = new Semester(semesterName, semesterStart, semesterEnd, currentSemester);
semesters.add(semester);
}
}
catch(Exception e){
}
finally {
if (c1 != null && !c1.isClosed()) {
c1.close();
}
}
return semesters;
}
public Semester getSemester(String semName){
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
Semester semester = new Semester();
try {
String mysql = "select * from semesters where SEMESTER_NAME=?";
String[] args = {semName};
Cursor cursor = db.rawQuery(mysql, args);
while (cursor.moveToNext()) {
semester = new Semester(cursor.getString(cursor.getColumnIndex(SEMESTER_NAME)), cursor.getString(cursor.getColumnIndex(SEMESTER_START)), cursor.getString(cursor.getColumnIndex(SEMESTER_END)), cursor.getInt(cursor.getColumnIndex(CURRENT_SEMESTER)));
}
db.setTransactionSuccessful();
return semester;
} catch (Exception e) {
return null;
} finally {
db.endTransaction();
return semester;
}
}
public Semester updateSemester(String oldName, String newName, String startDate, String endDate) throws ParseException {
SQLiteDatabase db = this.getReadableDatabase();
Semester semester = new Semester();
db.beginTransaction();
Date date1 = new SimpleDateFormat("MM/dd/yyyy").parse(startDate);
Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse(endDate);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date currentDate = new Date();
int currentSemester = 0;
if (date1.compareTo(currentDate) <= 0 && date2.compareTo(currentDate) >= 0)
currentSemester = 1;
try {
String mysql = "UPDATE semesters SET " + SEMESTER_NAME + "=\"" + newName + "\", " + SEMESTER_START + "=\"" + startDate + "\", " + SEMESTER_END + "=\"" + endDate + "\", " + CURRENT_SEMESTER + "=" + currentSemester + " WHERE " + SEMESTER_NAME + "=\"" + oldName + "\"";
semester = new Semester(newName, startDate, endDate, currentSemester);
db.execSQL(mysql);
db.setTransactionSuccessful();
} catch (Exception e) {
return null;
} finally {
db.endTransaction();
return semester;
}
}
public ArrayList<Course> getCourses(String semesterName){
ArrayList<Course> courses = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
String sql = "select * from courses WHERE SEMESTER=\"" + semesterName + "\"";
Cursor c1 = db.rawQuery(sql, null);
try{
while (c1.moveToNext()){
Course course = new Course(c1.getString(c1.getColumnIndex(COURSE_NAME)), c1.getString(c1.getColumnIndex(COURSE_ID)), Double.parseDouble(c1.getString(c1.getColumnIndex(COURSE_CREDITS))), c1.getString(c1.getColumnIndex(INSTRUCTOR_NAME)), c1.getString(c1.getColumnIndex(LOCATION)));
courses.add(course);
}
}
catch(Exception e){
}
finally {
if (c1 != null && !c1.isClosed()) {
c1.close();
}
}
return courses;
}
public Course addCourse(Semester semester, String courseName, String courseID, String credits, String color, String teacher, String location){
Course course = new Course();
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
// The user might already exist in the database (i.e. the same user created multiple posts).
ContentValues values = new ContentValues();
values.put(COURSE_NAME, courseName);
values.put(COURSE_ID, courseID);
values.put(COURSE_CREDITS, Double.parseDouble(credits));
values.put(COURSE_COLOR, color);
values.put(SEMESTER, semester.getName());
values.put(INSTRUCTOR_NAME, teacher);
values.put(LOCATION, location);
db.insertOrThrow(TABLE_COURSES, null, values);
course = new Course(courseName, courseID, Double.parseDouble(credits), teacher, location);
db.setTransactionSuccessful();
} catch (Exception e) {
return null;
} finally {
db.endTransaction();
return course;
}
}
}
最后,这是数据来自的第二个活动:
public class AddCourseActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private ActionBar actionBar;
private DatePickerDialog picker;
private int currentColor = 0;
private String[] colors = {"#006600", "#009933", "#0033cc", "#0099ff", "#b30000", "#cc2900", "#999900", "#cccc00", "#86b300", "#996633", "#7a7a52", "#9900ff", "#9966ff", "#cc0088", "#ff6699", "#006666", "#669999", "#333399", "#666699", "#000000"};
private ArrayList<ImageButton> imageButtons;
private Dialog myDialog;
private Semester semester;
private ArrayList<Course> courses;
private Spinner creditSpinner;
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_course);
Toolbar toolbar = (Toolbar) findViewById(R.id.view_courses_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Intent i = getIntent();
semester = (Semester)i.getSerializableExtra("semester");
courses = semester.getCourses();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.parseColor(colors[currentColor]));
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedSemester = parent.getItemAtPosition(position).toString();
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
Semester semester = databaseHelper.getSemester(selectedSemester);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void saveCourse(View view) {
boolean error = false;
EditText addName = (EditText)findViewById(R.id.addName);
EditText addID = (EditText)findViewById(R.id.addID);
EditText addTeacher = (EditText)findViewById(R.id.addInstructor);
EditText addLocation = (EditText)findViewById(R.id.addLocation);
TextView nameError = (TextView)findViewById(R.id.nameErrorText);
TextView idError = (TextView)findViewById(R.id.idErrorText);
String name = addName.getText().toString();
String id = addID.getText().toString();
if (name.isEmpty()) {
nameError.setText("*Course name can not be empty");
error = true;
}
if (id.isEmpty()) {
idError.setText("*ID can not be empty");
error = true;
}
ArrayList<Course> courses = semester.getCourses();
for (int i = 0; i < courses.size(); i++){
if (courses.get(i).getCourseName().equals(addName.getText().toString())){
nameError.setText("*A course with that name already exists");
error = true;
}
if (courses.get(i).getCourseName().equals(addName.getText().toString())){
idError.setText("*A course with that ID already exists");
error = true;
}
}
if (!error){
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
Course course = databaseHelper.addCourse(semester, name, id, creditSpinner.getSelectedItem().toString(), colors[currentColor], addTeacher.getText().toString(), addLocation.getText().toString());
semester.addCourse(course);
Intent returnIntent = new Intent();
returnIntent.putExtra("course",course);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
}
}
我发现该课程实际上已添加到数据库中,但它只是没有显示在 ListView 中。当我第一次启动活动并添加课程时,列表视图会在返回课程活动时更新。但是,在那之后,如果我添加任意数量的课程,它不会刷新。
【问题讨论】:
标签: java android-studio listview android-sqlite