Retrofit响应中的Android空指针异常

Nid*_*esh 5 api android callback nullpointerexception retrofit

在我的应用程序中,我一直在为我的网络服务调用使用改造。它工作正常,但是当应用程序进入后台时它崩溃并得到错误日志,

  java.lang.NullPointerException: Attempt to invoke interface method 'void    retrofit.Callback.failure(retrofit.RetrofitError)' on a null object   reference
    at retrofit.CallbackRunnable$2.run(CallbackRunnable.java:53)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:145)
    at android.app.ActivityThread.main(ActivityThread.java:5942)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)


Can anyone help me to overcome this issue..??
Run Code Online (Sandbox Code Playgroud)

这是我的改造客户端类,

public class RetrofitClient {
private static RetrofitCommonService RETROFIT_CLIENT;
public RetrofitClient() {}
public static RetrofitCommonService getInstance() {
    //if REST_CLIENT is null then set-up again.
    if (RETROFIT_CLIENT == null) {
        setupRestClient();
    }
    return RETROFIT_CLIENT;
}

private static void setupRestClient() {
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setClient(new OkClient(new OkHttpClient()))
            .setEndpoint(Constants.BASE_URL)
            //.setLogLevel(RestAdapter.LogLevel.FULL)
            .build();
    RETROFIT_CLIENT = restAdapter.create(RetrofitCommonService.class);
}
}
Run Code Online (Sandbox Code Playgroud)

这是我的改造服务界面,

 public interface RetrofitCommonService {

@FormUrlEncoded
@POST("/user")
void doRegistration(@Field("user[mobile_number]") String phone, @Field("user[new_uid]") String imei,
                    Callback<RetrofitResponse> response);

 }
Run Code Online (Sandbox Code Playgroud)

通过这种方式,我从我的活动和实施改造回调的活动中调用改造服务。

 RetrofitCommonService mRetrofitCommonService = RetrofitClient.getInstance();
    mRetrofitCommonService.doRegistration(mPhoneNumber, getDeviceId(), this);

public class RegistrationActivity extends Activity implements Callback<RetrofitResponse>{

}

@Override
public void success(RetrofitResponse retrofitResponse, Response response) {

      }

@Override
public void failure(RetrofitError error) {
}  
Run Code Online (Sandbox Code Playgroud)

Nid*_*esh 3

修复了这个问题

在我的活动中,我有两个 Retrofit 服务操作,这两个服务依赖相同的 Retrofit 回调方法。当一个服务尝试获取回调同时其他服务使用回调时,这些会导致空指针。我已经删除了回调方法并使用了 Retrofit 服务的返回对象。那么就不需要中继回调方法了。

这对我有用......