#java #android #google-app-engine #google-cloud-endpoints
#java #Android #google-app-engine #google-облако-конечные точки #google-cloud-конечные точки
Вопрос:
A NullPointerException
возникает в указанной строке моего метода endpoint api при вызове клиентом Android, но не при вызове из api explorer:
@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();
}
}
Переменные mUserId
и mReview
на стороне клиента не равны нулю при передаче в метод конечной точки в качестве параметров.
Как мне исправить эту ошибку?
Комментарии:
1. Вы уверены, что вызываете один и тот же экземпляр приложения? Вы регистрировали переменные, чтобы убедиться, что они не только не равны нулю, но и идентичны между вызовами?
2. Я отладил серверную часть, и все переменные идентичны и корректны, это действительно сбивает с толку.
3. Какая строка
NullPointerException
выбрасывается? (Можете ли вы поделиться с нами трассировкой стека?)4. java.lang. Исключение NullPointerException в com.neutronstar.backend. Endpoint.publishReview(Endpoint.java:62) в sun.reflect.NativeMethodAccessorImpl.invoke0(собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) в sun.reflect. Делегирование methodaccessorimpl.invoke(делегирование methodaccessorimpl.java:43) в java.lang.reflect. Method.invoke(Method.java:498) @Уилл Хейворт
5. Рад! Какая строка 62 в приведенном выше коде?