2015-09-15 31 views
-3

我正在使用library爲Android做我的應用程序和我的網站之間的HTTP通信。對於圖書館,它允許你創建一個靜態類,然後可以在整個應用程序中調用。如果不通過參數傳遞覆蓋方法

當你調用靜態類方法時,會發生什麼,基本上你只是將你的參數傳遞給它,其餘的(顯然)做。其中一個參數是AsyncHttpResponseHandler,它允許您覆蓋方法並處理其運行的AsyncTask的不同部分。

像這樣:內部類

靜態方法

public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { 
    client.get(getAbsoluteUrl(url, false), params, responseHandler); 
} 

,然後調用該方法(如實施例)時:

TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() { 
      @Override 
      public void onSuccess(int statusCode, Header[] headers, JSONObject response) { 
       // If the response is JSONObject instead of expected JSONArray 
      } 

      @Override 
      public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) { 
       // Pull out the first event on the public timeline 
       JSONObject firstEvent = timeline.get(0); 
       String tweetText = firstEvent.getString("text"); 

       // Do something with the response 
       System.out.println(tweetText); 
      } 
     }); 

其中一種方法即你可以覆蓋是onFailure()

我想知道的是,有沒有一種方法可以爲onFailure()覆蓋設置「默認」?我希望每次調用get(url, params, responseHandler)方法時都要設置相同的方法,而不必每次都重新聲明它,但我不知道有任何設置方法,但仍考慮到傳遞的AsyncHttpResponseHandler參數。

回答

1

您必須每次都告知@Override onFailure()是否必須(或不)執行onFailure成功。

您可以做的是創建一個實用程序方法/類來處理所有onFailure()請求。

例:

TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() { 
    // other methods overrides 

    @Override 
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { 
     FailureClass.handlerMethod(statusCode, headers, responseBody, error); 
    } 
} 

class FailureClass { 
    public static handlerMethod(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { 
     // do the common stuff, redirect or what you want... 
    } 
} 
+0

感謝。添加更多的代碼比理想,但它比每次重複相同的handlerMethod代碼更好! – CynePhoba12