Android Retrofit 响应中的空指针异常

Android Null Pointer Exception in Retrofit response

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

  java.lang.NullPointerException: Attempt to invoke interface method 'void    retrofit.Callback.failure(retrofit.RetrofitError)' on a null object   reference
    at retrofit.CallbackRunnable.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..??

这是我的 Retrofit 客户端 class,

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);
}
}

这是我的改造服务界面,

 public interface RetrofitCommonService {

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

 }

这样我就可以从我的 activity 和 activity 实现改造回调中调用改造服务。

 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) {
}  

已解决此问题

在我的 activity 中,我有两个 Retrofit 服务操作,这两个服务依赖于相同的 Retrofit Callback 方法。当一个服务试图在同一时间回调被其他服务使用时,这些会导致空指针。我已经删除了回调方法并使用了 Retrofit 服务中的 return 对象。然后不需要中继回调方法。

这对我有用...

在调用调用回调的方法之前,应正确初始化回调。