问题
主键是自增的,插入之后,对象的id并没有被赋值,搞不到对象的id。
解决
刚开始根据插入内容查找到该记录从而获取id,但是查看源码发现了更好的办法。
/**
* Convenience method for inserting a row into the database.
*
* @param table the table to insert the row into
* @param nullColumnHack optional; may be <code>null</code>.
* SQL doesn't allow inserting a completely empty row without
* naming at least one column name. If your provided <code>values</code> is
* empty, no column names are known and an empty row can't be inserted.
* If not set to null, the <code>nullColumnHack</code> parameter
* provides the name of nullable column name to explicitly insert a NULL into
* in the case where your <code>values</code> is empty.
* @param values this map contains the initial column values for the
* row. The keys should be the column names and the values the
* column values
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insert(String table, String nullColumnHack, ContentValues values) {
try {
return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);
} catch (SQLException e) {
Log.e(TAG, "Error inserting " + values, e);
return -1;
}
}
@return the row ID of the newly inserted row, or -1 if an error occurred
已经说得很明白了,insert方法的返回值就是新插入的记录的id,如果返回值是-1说明没插入成功。