【发布时间】:2015-11-22 08:22:58
【问题描述】:
您好,我是 Retrofit 和 Realm for Android 的新手,所以如果有任何愚蠢的代码,请多多包涵。
所以在这种情况下我有一个简单的 API 用于登录,这是我代码中的 User 对象:
public class User extends RealmObject {
@SerializedName("id")
private String ID;
@SerializedName("username")
private String username;
@SerializedName("token_type")
private String tokenType;
@SerializedName("token")
private String token;
//Setter and Getter goes here
}
登录API接口:
public interface LoginAPI {
@POST("api/v1/login")
Call<User> login(@Body JsonObject user);
}
这是对我的登录 API 的请求的实现:
//OnClickListener
View.OnClickListener loginButtonClicked = new View.OnClickListener() {
public void onClick(View v) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("username", emailEditText.getText().toString());
jsonObject.addProperty("password", passwordEditText.getText().toString());
Retrofit loginRequest = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginAPI loginAPI = loginRequest.create(LoginAPI.class);
Call<User> call = loginAPI.login(jsonObject);
call.enqueue(LoginFragment.this);
}
};
//API Callback
@Override
public void onResponse(Response<User> response, Retrofit retrofit) {
User user = response.body();
Realm realm = Realm.getInstance(getContext());
realm.beginTransaction();
realm.copyToRealmOrUpdate(user);
realm.commitTransaction();
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(getActivity(), "Failed " + t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
问题是它总是调用 onFailure 回调并且它为 Throwable t 值返回 NULL。
当我的用户对象没有扩展 RealmObject 时,我的代码可以工作,但这意味着我必须为 Retrofit 和 Realm 创建 2 个对象。
我有什么方法可以将 1 Object 用于 Retrofit 和 Realm 实现,或者我的代码中是否有任何错误或遗漏? 非常感谢。
【问题讨论】: