我不确定这是否是完美的称呼,但我能拿出最好的称呼。

我有一个Java类ApiRequest,它运行一些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


但这可以用于常规活动,因此确实让我处于优势。一个修复将不胜感激。我想说,这对我来说是一个可教的时刻。谢谢

最佳答案

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

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

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

10-06 03:40