【发布时间】:2014-03-27 14:14:25
【问题描述】:
我们正在使用 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;
}
【问题讨论】:
标签: android google-app-engine key entity google-cloud-endpoints