我有什么方法可以获取表行的下一个可用 ID(在表中插入行时会自动创建),所以我不会被迫在给定时间插入该行来获取它?
更准确地说:我有一个包含列表视图的活动,并且每个项目都是使用第二个活动添加的。当我在第二个活动中完成添加项目详细信息时,我通过一个可打包对象传递该项目(我将 Parcelable 接口实现到 DaoGenerator 创建的持有者类之一)。该对象的 id 值不能为空,使用 writeLong(id) 传递它,并在我的 Parcelable 方法中使用 readLong() 接收它,所以我必须通过插入当前项目来自动生成 id 值数据库。我想做的是:生成这些ID(不将项目插入数据库),将该项目传递给第一个活动,当用户决定从列表中保存所有这些项目时,我会将它们全部添加到数据库中单笔交易。
我有一些示例代码:
public class Question implements Parcelable {
private Long id;
private String questionContent;
// KEEP FIELDS - put your custom fields here
// KEEP FIELDS END
public Question() {
}
public Question(Long id) {
this.id = id;
}
public Question(Long id,String questionContent) {
this.id = id;
this.questionContent = questionContent;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// KEEP METHODS - put your custom methods here
// begin Parcelable implementation
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(questionContent);
}
public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {
public Question createFromParcel(Parcel in) {
return new Question(in);
}
public Question[] newArray(int size) {
return new Question[size];
}
};
private Question(Parcel in) {
id = in.readLong();
questionContent = in.readString();
}
// end Parcelable implementation
// KEEP METHODS END
}
这就是我创建项目并将其发送到列表的方式:
Question questionHolder = new Question(
null, etItemContent.getText().toString() .trim(),);
Log.d(LOG_TAG, "question id = "
+ questionHolder.getId());
// inserting it here, would auto-generate the ID I required,
// but I would like to do that to all of the items in the first Activity (containing the list of all of the items)
// questionDao.insert(questionHolder);
Log.d(LOG_TAG, "question id = "
+ questionHolder.getId());
// add item to intent
Bundle b = new Bundle();
b.putParcelable(IMPORTANCE_TAG, questionHolder);
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULT_OK, intent);
QuestionItemActivity.this.finish();