【问题标题】:Interface declared is NULL接口声明为 NULL
【发布时间】:2018-09-12 07:49:59
【问题描述】:

我正在使用 Retrofit HTTP 中间层进行 API 调用。由于 Retrofit 异步工作,我使用接口返回 API 响应。但声明的接口在 OnResponse() 中显示为 NULL Retrofit 的重写方法。

以下是代码块,

界面

public interface OnResponseListener{
        void getCountryListResponse(ArrayList<String> list,int responseCode);
    }

OnResponse

            @Override
            public void onResponse(Call<List<Country>> call, Response<List<Country>> response) {

                Log.d("Response",response.body().toString());
                for (Country country: response.body())
                {
                    Log.d("Country",country.toString());
                    Log.d("CommomName",country.getCommonName());
                   // Log.d("BLLL",country.getCommonName());
                   countryList.add(country.getCommonName());
                }
                Log.d("Entered","Vikas Entered");
              //  Log.d("ResonseListener",mResponseListener.toString());//Here throwing error, mResponseListener is null object
                mResponseListener.getCountryListResponse(countryList,response.code());
            }

接口声明

private  OnResponseListener mResponseListener;

我不知道为什么它是 NULL,即使在声明了 Object(Interface) 之后也是如此。任何帮助将不胜感激。

【问题讨论】:

  • 你能把onResponse的完整方法放在这里吗?
  • 你必须初始化监听器
  • 你只创建了它的对象。你还没有注册你的接口。
  • 嗨@Piyush,如何注册接口。??我们不能像类一样初始化接口,对吧..?

标签: java android interface retrofit2


【解决方案1】:

我有很多建议给你。

  • 如果不初始化,Java 中的每个对象都是空的。见this answer
  • 你会为 100 种类型的响应制作 100 个OnResponseListener 接口吗?这就是Java Generics 来现场的原因。
  • 您为什么不创建一个通用类来为您拨打电话并给出预期的响应?

我正在展示我的班级,这将清除所有这些要点

调用webservice的代码就是这样。

如果您有 BaseModel 类型的响应。

Call<BaseModel> call;
new RetroService().call(call, new RetroService.OnResponseListenerRetro<BaseModel>() {
    @Override
    public void onSuccess(String tag, BaseModel response) {
        System.out.println(response);
    }

    @Override
    public void onError(String tag, RetroService.ErrorType error) {
        Toast.makeText(, "", Toast.LENGTH_SHORT).show();
    }
});

如果您有 Model2 类型响应。

Call<Model2> call;
new RetroService().call(call, new RetroService.OnResponseListenerRetro<Model2>() {
    @Override
    public void onSuccess(String tag, Model2 response) {
        System.out.println(response);
    }

    @Override
    public void onError(String tag, RetroService.ErrorType error) {
        Toast.makeText(, "", Toast.LENGTH_SHORT).show();
    }
});

现在你只需要创建这个类。

RetroService.java

import android.support.annotation.Nullable;
import android.util.Log;

import com.arsdigitech.angpau.R;
import com.arsdigitech.angpau.appClasses.App;
import com.google.gson.JsonSyntaxException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class RetroService {
    public static final String TAG = "RetroService***";

    public <T> void call(Call<T> call, OnResponseListenerRetro<T> onResponseListener) {
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if (response.isSuccessful()) {
                    onResponseListener.onSuccess("", response.body());
                } else {
                    ErrorType errorType = ErrorType.getErrorTypeByVolleyError(response.code());
                    onResponseListener.onError("", errorType);
                }
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                Log.e(TAG, t.getMessage());
                if (t instanceof JsonSyntaxException) {
                    onResponseListener.onError("", ErrorType.ParseError);
                } else {
                    onResponseListener.onError("", ErrorType.Error);
                }
            }
        });
    }


    public enum ErrorType {
        Error(R.string.error),
        RequestTimeoutError(R.string.timeoutError),
        NoConnectionError(R.string.noConnectionError),
        AuthFailureError(R.string.authFailureError),
        ServerError(R.string.serverError),
        NetworkError(R.string.networkError),
        BadRequestError(R.string.badRequestError),
        ForbiddenError(R.string.forbiddenError),
        NotFoundError(R.string.notFoundError),
        UnsupportedMediaType(R.string.unsupportedMediaType),
        MethodNotAllowedError(R.string.methodNotAllowedError),
        ParseError(R.string.parsing_error),;
        int message;

        ErrorType(int message) {
            this.message = message;
        }

        public String getMessage() {
            return App.getAppRes().getString(message);
        }

        public static @Nullable
        ErrorType getErrorTypeByVolleyError(int errorCode) {
            ErrorType errorType = null;
            switch (errorCode) {
                case 400:
                    errorType = ErrorType.BadRequestError;
                    break;
                case 401:
                    errorType = ErrorType.AuthFailureError;
                    break;
                case 403:
                    errorType = ErrorType.ForbiddenError;
                    break;
                case 404:
                    errorType = ErrorType.NotFoundError;
                    break;
                case 408:
                    errorType = ErrorType.RequestTimeoutError;
                    break;
                case 500:
                case 501:
                case 502:
                case 503:
                case 504:
                case 505:
                    errorType = ErrorType.ServerError;
                    break;
                default:
                    errorType = ErrorType.Error;
            }
            return errorType;
        }
    }

    public interface OnResponseListenerRetro<T> {
        void onSuccess(String tag, T response);
        void onError(String tag, ErrorType error);
    }

}

【讨论】:

  • 谢谢Khemraj。我理解这个问题。
【解决方案2】:

您必须在其中设置值,并从您调用它的地方实现它:

创建一个方法:

public void setResponseListener(OnResponseListener mResponseListener){
    this.mResponseListener = mResponseListener;
}

并从你调用这个 call.enqueue() 方法的地方调用它,就像下面的注册一样 :

    RestClientClassObject.setResponseListener(new OnResponseListener() {
        @Override
        void getCountryListResponse(ArrayList<String> list, int responseCode) {

            //write code you want to do with list

        }

    });

【讨论】:

  • 嗨@NehaK,什么是 RestClientClassObject .??我正在使用 Retrofit 进行 HTTP 请求和响应。
  • 请把你写过 onResponse() 的课程贴出来,我会告诉你怎么做
猜你喜欢
  • 2012-05-17
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 2019-07-16
  • 2021-12-01
  • 2013-11-13
  • 1970-01-01
相关资源
最近更新 更多