我目前正在尝试通过查询提供适配器的SQLite数据库来填充ListView,我可以通过添加条目来更新。但是,除非我重新启动应用程序,否则ListView不会更新。
这是我的数据源代码:
public class DataSource {
// Database fields
private SQLiteDatabase database;
private SQLHelper dbHelper;
private String[] allColumns = null;
public DataSource(Context context) {
dbHelper = new SQLHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Person addPerson(String firstname, String lastname) {
ContentValues values = new ContentValues();
values.put(SQLHelper.COLUMN_FIRSTNAME, firstname);
values.put(SQLHelper.COLUMN_LASTNAME, lastname);
long insertId = database.insert(SQLHelper.TABLE_PEOPLE, null, values);
Cursor cursor = database.query(SQLHelper.TABLE_PEOPLE, allColumns, SQLHelper.COLUMN_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
Person newPerson = cursorToPerson(cursor);
cursor.close();
return newPerson;
}
public List<Person> getAllPeople() {
List<Person> people = new ArrayList<Person>();
Cursor cursor = database.query(SQLHelper.TABLE_PEOPLE, allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Person person = cursorToPerson(cursor);
people.add(person);
cursor.moveToNext();
}
cursor.close();
return people;
}
private Person cursorToPerson(Cursor cursor) {
if(cursor.getCount() > 0) {
Person person = new Person();
person.setId(cursor.getLong(0));
person.setFirstname(cursor.getString(1));
person.setLastname(cursor.getString(1));
return person;
}
return null;
}
}
这是SQLHelper:
public class SQLHelper extends SQLiteOpenHelper {
// Database
private static final String DATABASE_NAME = "people.db";
private static final int DATABASE_VERSION = 1;
// Table
public static final String TABLE_PEOPLE = "people";
// Columns
public static final String COLUMN_ID = "_id";
public static final String COLUMN_FIRSTNAME = "first_name";
public static final String COLUMN_LASTNAME = "last_name";
// Database creation sql statement
private static final String DATABASE_CREATE = "create table " + TABLE_PEOPLE + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_FIRSTNAME + " text not null, " + COLUMN_LASTNAME + " text not null);";
public SQLHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(SQLHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PEOPLE);
onCreate(db);
}
}
要填充我的ListView适配器,我调用getAllPeople()
方法。要添加到我的数据库,我调用addPerson()
方法。 ListView位于对话框中。
为什么我必须重新启动我的应用程序才能让新人更新ListView,这是否有任何特殊原因?
答案 0 :(得分:3)
您必须通知适配器有关更改的数据。根据适配器的类型,您需要拨打for (x <- xs; y <- x * x) yield y
或swapCursor()
答案 1 :(得分:1)
每次添加Person时都调用notifyDataSetChanged吗?