2017-08-31 13 views
0

上被称为我有一个EditText这有利于谷歌地图的地方自动完成。 它抛出这个错误:错误:等待一定不要在UI线程

await must not be called on the UI thread. 

在改变了的EditText文本中,AutoCompletePlace API调用。
我该如何解决这个问题?

@Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      try { 
       GeoDataApi geoDataApi = Places.GeoDataApi; 
       PendingResult<AutocompletePredictionBuffer> autocompletePredictions = geoDataApi. 
         getAutocompletePredictions(GoogleClient.getIstance(), searchLoc.getText().toString(), null, null); 
       AutocompletePredictionBuffer autocompletePredictionBuffer= autocompletePredictions.await(); 
       System.out.println("Size: " + autocompletePredictionBuffer.getCount()); 
       for(int i=0; i<autocompletePredictionBuffer.getCount(); i++){ 
        Place p= (Place) geoDataApi. 
          getPlaceById(GoogleClient.getIstance(), autocompletePredictionBuffer.get(i).getPlaceId()); 
        searchList.add(
          new SearchListProvider(
            R.mipmap.ic_launcher, 
            autocompletePredictionBuffer.get(i).getFullText(null).toString(), 
            p) 
        ); 

       } 


      } 
      catch (Exception e){ 

       e.printStackTrace(); 
       System.out.println("Message: "+e.getMessage()); 
       Log.d("Message: ", e.getMessage()); 
      } 
      Toast.makeText(getContext(), searchLoc.getText(), Toast.LENGTH_SHORT).show(); 
     } 

回答

1

我认为你应该在这里使用AsyncTask。因为await正在停止当前线程。所以你应该发送你的请求到工作线程中的API。然后,你可以在onPostExecute()

+0

AutocompletePredictionBuffer autocompletePredictionBuffer = autocompletePredictions.await()更新结果; -----我应该在异步任务中执行此操作。 –

+0

@ShubhamAgarwalBhewanewala这将是确定的,如果你只是把所有相关的逻辑到doInBackground。 –

+0

我有,我在呼唤一个类似的问题'OptionalPendingResult .await()'我的活动的'的onCreate()'方法中。将它移动到一个'AsyncTask'解决了这个问题。 对于情况下,我必须执行一组检查以确定用户和应用程序是在什么状态,并将其转发给正确的活动的活动。其中一部分是使用'GoogleSignInApi.silentSignIn()'谷歌的标志,在无声身份验证检查,这就需要你使用'等待()'。 –