2017-09-26 8 views
0

나는 안드로이드와 구글 자동 완성 장소 API를 사용하고 난 할 노력하고있어 것은 해요 :싱글 OkHtpp 클래스를 생성하고 처리하는 방법 이전 요청

  1. 때마다 사용자가 글고의 내부에 문자를 입력 예측 결과를 얻기 위해 새로운 요청을해야합니다.
  2. 내가 필요한 유일한 결과는 사용자가 입력 한 최종 주소/위치이므로 이전 요청을 취소해야합니다.
  3. 그런 다음 위치 길이가 3 자 미만인 경우 RecyclerView를 정리하기 위해 일부 논리로 해결하십시오. 나는 싱글 인스턴스를해야하는 이유, 내가 시도 것

이 :

public class OkHttpSingleton extends OkHttpClient { 
private static OkHttpClient client = new OkHttpClient(); 

public static OkHttpClient getInstance() { 
    return client; 
} 

public OkHttpSingleton() {} 

public void CloseConnections(){ 
    client.dispatcher().cancelAll(); 
} 
public List<PlacePredictions> getPredictions(){ 
    //// TODO: 26/09/2017 do the request! 
    return null; 
} 

}

하지만이 때문에 doc에, 할 수있는 올바른 방법입니다 있는지 확실하지 않습니다 그것은 dispatcher().cancelAll() 메서드가 모든 요청을 취소한다고 말합니다.하지만 그 방법이 잘못되었다는 것을 알고 있습니다! 나는 싱글 톤을 만들고 나머지를 만드는 방법에 더 관심이있다.

메인 활동 :

Address.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
      if(s.length() > 3){ 
       _Address = Address.getText().toString(); 
       new AsyncTask<Void, Void, String>() { 
        @Override 
        protected void onPreExecute() { 
         super.onPreExecute(); 
        } 

        @Override 
        protected String doInBackground(Void... params) { 
         try { // request... 
        }else{Clear the RecyclerView!} 

답변

1

당신은 하나 OkHttpClient을 유지하는 싱글 도우미 클래스를 구현하고이 하나의 특정 클라이언트 사용하여 사용자 정의 기능을 모두 커버 할 수있다 :

public class OkHttpSingleton { 

    private static OkHttpSingleton singletonInstance; 

    // No need to be static; OkHttpSingleton is unique so is this. 
    private OkHttpClient client; 

    // Private so that this cannot be instantiated. 
    private OkHttpSingleton() { 
     client = new OkHttpClient.Builder() 
      .retryOnConnectionFailure(true) 
      .build(); 
    } 

    public static OkHttpSingleton getInstance() { 
     if (singletonInstance == null) { 
      singletonInstance = new OkHttpSingleton(); 
     } 
     return singletonInstance; 
    } 

    // In case you just need the unique OkHttpClient instance. 
    public OkHttpClient getClient() { 
     return client; 
    } 

    public void closeConnections() { 
     client.dispatcher().cancelAll(); 
    } 

    public List<PlacePredictions> getPredictions(){ 
     // TODO: 26/09/2017 do the request! 
     return null; 
    } 
} 

예를 사용 :

OkHttpSingleton localSingleton = OkHttpSingleton.getInstance(); 
... 
localSingleton.closeConnections(); 
... 
OkHttpClient localClient = localSingleton.getClient(); 
// or 
OkHttpClient localClient = OkHttpSingleton.getInstance().getClient(); 
+0

또 하나 질문이 있습니다. 어떻게하면 closeConnectio에 액세스 할 수 있습니까? ns' 및 getPredictions()? –

+0

'localClient.closeConnections()'? – Mehmed

+0

개체에 의해 찾지 못했습니다! –