2017-09-14 44 views
1

我指的是Google Places photo android api。 我在RecyclerView適配器的onBindViewHolder中使用下面的代碼。 它有一半的時間拋出非法狀態異常。請幫忙。illegalStateException從GeoDataClient.getPlacePhotos()獲取照片時

final Task<PlacePhotoMetadataResponse> photoMetadataResponse = mGeoDataClient.getPlacePhotos(placeId); 
     photoMetadataResponse.addOnCompleteListener(new OnCompleteListener<PlacePhotoMetadataResponse>() { 
      @Override 
      public void onComplete(@NonNull Task<PlacePhotoMetadataResponse> task) { 
       // Get the list of photos. 
       PlacePhotoMetadataResponse photos = task.getResult(); 
       // Get the PlacePhotoMetadataBuffer (metadata for all of the photos). 
       PlacePhotoMetadataBuffer photoMetadataBuffer = photos.getPhotoMetadata(); 
       // Get the first photo in the list. 
       PlacePhotoMetadata photoMetadata = photoMetadataBuffer.get(0); 
       // Get the attribution text. 
       CharSequence attribution = photoMetadata.getAttributions(); 
       // Get a full-size bitmap for the photo. 
       Task<PlacePhotoResponse> photoResponse = mGeoDataClient.getPhoto(photoMetadata); 
       photoResponse.addOnCompleteListener(new OnCompleteListener<PlacePhotoResponse>() { 
        @Override 
        public void onComplete(@NonNull Task<PlacePhotoResponse> task) { 
         PlacePhotoResponse photo = task.getResult(); 
         Bitmap bitmap = photo.getBitmap(); 
         ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
         bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 
         Glide.with(mContext) 
           .load(stream.toByteArray()) 
           .asBitmap() 
           .error(R.drawable.cast_album_art_placeholder) 
           .centerCrop() 
           .thumbnail(.2f) 
           .into(holder.placeImage); 

        } 
       }); 
      } 
     }); 

堆棧跟蹤:

E/UncaughtException: java.lang.IllegalStateException 
                   at com.google.android.gms.common.internal.zzbp.zzbg(Unknown Source) 
                   at com.google.android.gms.common.data.zzc.zzbu(Unknown Source) 
                   at com.google.android.gms.common.data.zzc.<init>(Unknown Source) 
                   at com.google.android.gms.location.places.internal.zzav.<init>(Unknown Source) 
                   at com.google.android.gms.location.places.internal.zzar.<init>(Unknown Source) 
                   at com.google.android.gms.location.places.PlacePhotoMetadataBuffer.get(Unknown Source) 

回答

1

我相當肯定,問題是,你的應用程序崩潰是由於事實,你正試圖檢索位置的照片並沒有照片顯示。在嘗試檢索photoMetadataBuffer.get(0)中的第一張照片之前,您必須先進行空白檢查。這是一個很好的例子,說明Google的文檔在提供的示例代碼中有些不完整。你應該有類似以下內容:

// Get the first photo in the list. 
if (photoMetadataBuffer != null) { 
    PlacePhotoMetadata photoMetadata = photoMetadataBuffer.get(0); 
// continue with your code 
} 

如果photoMetadataBuffer爲空,那麼就沒有要顯示的照片,你可以適當地處理應用程序邏輯,例如加載默認的圖像,提供反饋到用戶,或不顯示ImageView。