java - 接口(interface)声明为NULL

标签 java android interface retrofit2

我正在使用 Retrofit HTTP 中间层进行 API 调用。由于 Retrofit 是异步工作的,因此我使用一个接口(interface)来返回 API 响应。但是声明的接口(interface)在 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());
            }

接口(interface)声明

private  OnResponseListener mResponseListener;

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

最佳答案

我有很多建议给你。

  • 如果不初始化,Java 中的每个对象都是 null。请参阅this answer .
  • 您会为 100 种类型的响应创建 100 个 OnResponseListener 接口(interface)吗?这就是为什么Java Generics来到现场。
  • 为什么不创建一个公共(public)类来为您调用电话并给出预期的响应?

我正在展示我的类(class),它将清除所有这些要点

调用网络服务的代码就是这样。

如果您有 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);
    }

}

关于java - 接口(interface)声明为NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52290077/

相关文章:

node.js - 从不同的包实现接口(interface)(从其他模块回调)

java - Gen-Class 不生成 .class 文件

java - 高负载场景下DatabaseAccessor未连接

java - 无法将 Spring Boot 应用程序启动到 Linux 服务器

android - 在后台获取 GoogleMap 快照

java - 如何将 Activity 传递给 Fragment 中的 newInstance

java - Android 中工具栏与元素重叠

java - 如何移动选项卡式 Pane 的位置

android - Android应用程序崩溃诊断

python,动态实现一个类onthefly