使用Retrofit发布时,Realm对象为空

时间:2015-07-23 17:00:37

标签: android retrofit realm

我尝试将realm对象传递给改进put方法。虽然没有其他的线程错误,但不知何故改造是在没有来自领域对象的数据的情况下传递空对象。用户扩展了Realm Object。

这是改造方法:

    @Headers("Content-Type: application/json") @PUT(USER + "/{id}") Observable<Profile> editUser(@Body User user, @Path("id") String id);

这就是我在活动中打电话的方式:

if (!name.getText().toString().isEmpty()
    && !email.getText().toString().isEmpty()
    && !phone.getText().toString().isEmpty()) {
  realm.beginTransaction();
  agent.setName(name.getText().toString());
  agent.setPhone(phone.getText().toString());
  agent.setEmail(email.getText().toString());
  realm.commitTransaction();

  ConsumerRestAdapter.getService(this)
      .editUser(agent, agent.getId())
      .subscribeOn(Schedulers.newThread())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Observer<Profile>() {
        @Override public void onCompleted() {
          fillValues();
        }

        @Override public void onError(Throwable e) {
          Timber.tag("Profile Editing onError").e(e.getLocalizedMessage());
        }

        @Override public void onNext(Profile profile) {
          realm.beginTransaction();
          realm.where(User.class).findAll().clear();
          realm.copyToRealm(profile.getUser());
          agent = profile.getUser();
          realm.commitTransaction();
        }
      });
}

但是当我检查改装日志时,传递给服务器的对象是空对象。

    {"created_at":0,"has_password":false,"is_admin":false,"updated_at":0}

1 个答案:

答案 0 :(得分:1)

哦......我忘了我正在拦截GSON标题。所以这是我的答案。

public RestAdapter normalRestAdapter() {

//let gson ignore realm object
Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
  @Override public boolean shouldSkipField(FieldAttributes f) {
    return f.getDeclaringClass().equals(RealmObject.class);
  }

  @Override public boolean shouldSkipClass(Class<?> clazz) {
    return false;
  }
}).create();

//okhttp to read cookie from server
okHttpClient.setCookieHandler(
    new CookieManager(persistentCookieStore, CookiePolicy.ACCEPT_ALL));

RestAdapter restAdapter;

if (BuildConfig.DEBUG) {
  restAdapter = new retrofit.RestAdapter.Builder().setEndpoint(BASE_URL)
      .setConverter(new GsonConverter(gson))
      .setLogLevel(RestAdapter.LogLevel.FULL)
      .setClient(new OkClient(okHttpClient))
      .setRequestInterceptor(new NNRequestInterceptor())
      .setErrorHandler(new RetrofitErrorHandler(mContext))
      .build();
} else {
  restAdapter = new retrofit.RestAdapter.Builder().setEndpoint(BASE_URL)
      .setConverter(new GsonConverter(gson))
      .setClient(new OkClient(okHttpClient))
      .setErrorHandler(new RetrofitErrorHandler(mContext))
      .build();
}

return restAdapter;

}

解决方案是我创建了新的User对象并将其传递给改进版。

User user = new User();

现在有效。