有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Tablayout片段的java实现接口(Android)

我不确定这是一个完美的标题,但这是我能想出的最好的

我有一个java类APIREST,它运行一些http请求,并通过接口在回调中返回结果。下面的验证方法就是一个示例:

public class ApiRequest {

     private Context context;
     private ApiRequestCallback api_request_callback;

    public ApiRequest ( Context context ){
       this.context = context;

       // this can either be activity or context. Neither works in fragment
       // but does in activity
       this.api_request_callback = ( ApiRequestCallback ) context;
    }

 public interface ApiRequestCallback {
    void onResponse(JSONObject response );
    void onErrorResponse(JSONObject response );
}

public JsonObject authenticate(){
   .... do stuff and when you get response from the server. This is some 
   kinda of async task usually takes a while

   // after you get the response from the server send it to the callback
   api_request_callback.onResponse( response );
}

现在我在tablayout中有一个fragment类,它实现了下面这个类

public class Home extends Fragment implements ApiRequest.ApiRequestCallback 
{

  // I have tried
  @Override
   public void onViewCreated(.........) {
      api_request = new ApiRequest( getContext() );
   }


   // and this two
   @Override
   public void onAttach(Context context) {
      super.onAttach(context);
      api_request = new ApiRequest( context );
   }

   @Override
public void onResponse(JSONObject response) {
   //I expect a response here
}

}

我得到的回应是,我无法将活动上下文强制转换为接口

Java.lang.ClassCastException: com.*****.**** cannot be cast to com.*****.****ApiRequest$ApiRequestCallback

但这是一项有规律的活动,所以它真的让我很紧张。对此的修复将不胜感激。我想说,这对我来说是一个可教的时刻。谢谢


共 (1) 个答案

  1. # 1 楼答案

    要构造ApiRequest对象,需要传递上下文。在构造函数中,您假设始终可以将此上下文强制转换为ApiRequestCallback(这是您正在执行的错误)。就像在片段中一样,片段没有自己的上下文,当您在片段中使用getContext()时,它将返回父活动的上下文,而ApiRequest类的构造函数中的上下文不能转换为ApiRequestCallback

    将APIRESQUEST构造函数更改为以下内容:

    public ApiRequest (Context context, ApiRequestCallback api_request_callback){
           this.context = context;
           this.api_request_callback = api_request_callback;
    }
    

    然后在片段中使用以下内容:

    api_request = new ApiRequest(getContext(), Home .this);