我们正在用GAE实现一个android项目,我们在AppEngine项目中创建了一个实体,我们希望在客户端使用它。我们需要检索刚刚创建的实体的密钥。
实体代码:
@Entity
public class Poll {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key keyPoll;
private String title;
private String creator;
private Date creationDate;
private String close;
public Key getKeyPoll() {
return keyPoll;
}
public String getTitle() {
return title;
}
public String getCreator() {
return creator;
}
public Date getCreationDate() {
return creationDate;
}
public String getClose() {
return close;
}
public void setTitle(String title) {
this.title = title;
}
public void setCreator(String creator) {
this.creator = creator;
}
public void setCreationDate(Date date) {
creationDate = date;
}
public void setClose(String state) {
close = state;
}
}
客户代码:
private class PollTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
//Entity creation
Poll poll = new Poll();
poll.setCreator("Bill");
poll.setCreationDate(new DateTime(System.currentTimeMillis()));
poll.setTitle(title);
poll.setClose("n");
Pollendpoint.Builder builder = new Pollendpoint.Builder(
AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
null);
builder = CloudEndpointUtils.updateBuilder(builder);
Pollendpoint endpoint = builder.build();
try {
endpoint.insertPoll(poll).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//this is another entity that store in its field "pollK" the key of
// the previous entity "poll"
PollImg pollImg = new PollImg();
pollImg.setPollK(poll.getKeyPoll());
pollImg.setImageK(imageKey);
Pollimgendpoint.Builder imgBuilder = new Pollimgendpoint.Builder(
AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
null);
imgBuilder = CloudEndpointUtils.updateBuilder(imgBuilder);
Pollimgendpoint imgEndpoint = imgBuilder.build();
try {
imgEndpoint.insertPollImg(pollImg).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
问题是poll.getKeyPoll()返回一个空值,即使实体“poll”在服务器上正确创建并可见。
insertPoll方法代码:
/**
* This inserts a new entity into App Engine datastore. If the entity already
* exists in the datastore, an exception is thrown.
* It uses HTTP POST method.
*
* @param poll the entity to be inserted.
* @return The inserted entity.
*/
@ApiMethod(name = "insertPoll")
public Poll insertPoll(Poll poll) {
EntityManager mgr = getEntityManager();
try {
mgr.persist(poll);
} finally {
mgr.close();
}
return poll;
}
答案 0 :(得分:0)
更正的答案:从您显示的代码中,对象poll
是您首先创建的本地对象,然后通过线路将其发送到App Engine后端。您的insertPoll
方法看起来不错。
但是,您不能指望代码会自动填充poll
对象的Key字段,因为该对象仍然是本地的,仅此而已。要检索实际值,您需要查看代码中endpoint.insertPoll(poll).execute();
的响应值。这将返回Poll对象,然后您可以查询该对象以获取Key值。