2017-01-07 95 views
0

我學會了如何從圖庫中選擇一張圖片,如何將圖片上傳到firebase存儲並將其顯示在onActivityResult中,一切正常。我的問題是,當我重新開始活動時,圖像消失了。這是我的代碼:如何使用Android獲取Firebase存儲中上次上傳圖片的路徑?

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 

    if (requestCode == PICK_PHOTO && resultCode == RESULT_OK) { 
     Uri uri = data.getData(); 

     StorageReference photoStorageReference = storageReference.child("Photos").child(uri.getLastPathSegment()); 
     String path = storageReference.getPath(); //get the path of the last uploaded image 
     photoStorageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
      @Override 
      public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
       Uri downloadUri = taskSnapshot.getDownloadUrl(); 
       Picasso.with(StorageActivity.this).load(downloadUri).fit().centerCrop().into(imageView); 
      } 
     }); 
    } 
} 

我已經創建了一個名爲displayLastImage()的方法。當我把這個方法從onCreate這樣的:

private void displayLastImage() { 
    StorageReference newStorageReference = storageReference.child("Photos/car.jpg"); 
    Glide.with(this).using(new FirebaseImageLoader()).load(newStorageReference).into(imageView); 
} 

完美的作品,但是當我從onCreate使用path代替"Photos/46"這樣調用方法:

private void displayLastImage() { 
    StorageReference newStorageReference = storageReference.child(path); 
    Glide.with(this).using(new FirebaseImageLoader()).load(newStorageReference).into(imageView); 
} 

我得到這個錯誤: java.lang.IllegalArgumentException: childName cannot be null or empty。我如何獲得上次上傳的圖片的path,以便我可以正確顯示它?

在此先感謝!

回答

0

當您上傳圖片時,會將其存儲在基於用戶從圖庫中選擇的圖片的路徑中。

String path = storageReference.getPath(); 

當您重新啓動活動,路徑將不會被初始化,所以你要查找的圖像在一個未知的路徑。

這意味着您需要「記住」對活動調用之間的路徑。您可以將其存儲在應用的共享首選項中。這些在活動之間堅持不懈。

更常見的是將圖像路徑(或其下載URL)存儲在雲存儲中,例如Firebase數據庫。你可以在Firebase Codelab for Android中看到一個例子。

+0

我已將圖片路徑存儲在Firebase數據庫中,現在我可以正確檢索它。完美的作品!非常感謝你弗蘭克! –

相關問題