2017-04-23 69 views
3

我正在開發android應用程序,用戶點擊圖像,它被存儲在firebase中,雲功能處理這個圖像,並以文本文件的形式將輸出存儲回firebase。爲了在android中顯示輸出,應用程序會不斷檢查輸出文件是否存在。如果是,那麼它在應用程序中顯示輸出。如果否,我必須一直等待文件,直到它可用。如何從Android應用程序檢查Firebase存儲中是否存在文件?

我無法找到任何文件來檢查Firebase中是否存在任何文件。任何幫助或指針都會有所幫助。

謝謝。

回答

1

Firebase存儲API的設置方式是用戶只請求存在的文件。

因此不存在的文件將作爲錯誤進行處理:

您可以查看文檔here

1

您可以使用getDownloadURL它返回一個承諾,這又可以用來捕獲一個「找不到」的錯誤,或者處理文件(如果存在)。例如:

storageRef.child("file.png").getDownloadURL().then(onResolve, onReject); 

function onResolve(foundURL) { 
//stuff 
} 
function onReject(error){ 
//fill not found 
console.log(error.code); 
} 

更新

這又是一個簡單,清晰的解決方案。

storageRef.child("users/me/file.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { 
    @Override 
    public void onSuccess(Uri uri) { 
        // Got the download URL for 'users/me/profile.png' 
    } 
}).addOnFailureListener(new OnFailureListener() { 
    @Override 
    public void onFailure(@NonNull Exception exception) { 
        // File not found 
    } 
}); 
+0

代碼謝謝您的回答。你能告訴我們上面使用的「then」成員的java版本嗎? –

+0

它是預定義的功能。如果遇到問題,請參閱最新的答案。 –

+0

感謝您的快速響應。我們嘗試使用更新後的答案,但在調試時我們發現,除非文件在存儲中可用,否則控件不會轉到上述答案中的任何方法。 –

0

我這個

void getReferenceAndLoadNewBackground(String photoName) { 
    final StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Photos").child(photoName + ".png"); 
    storageReference.getDownloadUrl() 
      .addOnSuccessListener(new OnSuccessListener<Uri>() { 
       @Override 
       public void onSuccess(Uri uri) { 
        loadBackground(storageReference); 
       } 
      }) 
      .addOnFailureListener(new OnFailureListener() { 
       @Override 
       public void onFailure(@NonNull Exception exception) { 
        int errorCode = ((StorageException) exception).getErrorCode(); 
        if (errorCode == StorageException.ERROR_OBJECT_NOT_FOUND) { 
         StorageReference storageReference2 = FirebaseStorage.getInstance().getReference().child("Photos").child("photo_1.png"); 
         loadBackground(storageReference2); 
        } 

       } 
      }); 
} 
相關問題