当我的端点api方法的指示行发生NullPointerException
时,由android客户端调用,而不是从api资源管理器调用时:
@ApiMethod(name = "publishReview", path = "publish-review", httpMethod = ApiMethod.HttpMethod.POST)
public Review publishReview(@Named("userId") final String id, ReviewForm reviewForm) {
Key<Profile> profileKey = Key.create(Profile.class, id);
final Key<Review> reviewKey = factory().allocateId(profileKey, Review.class);
final Long reviewId = reviewKey.getId();
Profile user = ofy().load().key(profileKey).now();
Review review = new Review(reviewId, id, reviewForm);
user.addToMyReviews(reviewId); // NULLPOINTER HERE
ofy().save().entities(review, user).now();
return review;
}
以下是addToMyReviews(Long reviewId)
:
public void addToMyReviews(final Long reviewId) {
if (!myReviews.contains(reviewId))
myReviews.add(reviewId);
}
这是端点方法的android客户端调用:
public static class PublishReview extends AsyncTask<Void, Void, String> {
private static MyApi myApiService = null;
private ReviewForm mReview;
private final String mUserId;
private Context mContext;
public PublishReview(final String userId, ReviewForm review, Context context) {
mReview = review;
mUserId = userId;
mContext = context;
}
@Override
protected String doInBackground(Void... params) {
if (myApiService == null) { // Only do this once
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
myApiService = builder.build();
}
try {
return myApiService.publishReview(mUserId, mReview).execute().getTitle();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String title) {
Toast.makeText(mContext, title + " published", Toast.LENGTH_LONG).show();
}
}
当作为params传递给端点方法时,客户端上的mUserId
和mReview
变量不为null。
如何解决此错误?