0.修改dataClass
因為我們要變成多張了,所以我們要把原本的String,改成List,新增以下
val photoUriList: List<String>? = null
1. 修改Intent
我們原本是單選,現在我們要把它新增成為可以選擇多樣的方式,直接在AddInvitationFragment裡面的 checkPermission(),修改Intent
val intent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true)
resultLauncher.launch(intent)
2.修改resultLauncher
再過來我們也要去我們的resultLauncher修改成拿到多張照片,原本拿到的方式是data.data(拿到一張),現在我們現在透過data.clipData就可以拿到多張照片啦!
private val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ uri ->
if (uri.resultCode == Activity.RESULT_OK){
val selectedUri = uri.data?.clipData
if (selectedUri != null){
val list = mutableListOf<Uri>()
val account = selectedUri.itemCount
//在這邊把它加入list
for (i in 0 until account){
val model = selectedUri.getItemAt(i).uri
list.add(model)
//並傳入viewModel
matchingViewModel.saveImageToFireStorage(requireActivity(),this,list)
3.修改saveImageToFireStorage()
看了一下Firebase的文檔,好像沒有一次上傳多張照片的方式,所以這邊就用for loop 分次上傳,且因為Firebase會自動異步,所以我們在上傳成功的時候,判斷是否全部都傳完了,傳完了就把資料丟進Fragment
//我們要把傳入的單筆url改成list
fun saveImageToFireStorage(activity: Activity, fragment: AddInvitationFragment, list: List<Uri>) {
val newList = mutableListOf<Uri>()
for (i in list.indices){
val sdf: StorageReference = FirebaseStorage.getInstance().reference.child(
Constant.PET_IMAGE + "_" + System.currentTimeMillis() + "_" + Constant.getFileExtension(
activity,
list[i]
sdf.putFile(list[i])
.addOnSuccessListener { it ->
it.metadata?.reference?.downloadUrl
?.addOnSuccessListener { uri ->
newList.add(uri)
Timber.d("測試 uri: $uri")
if (i == list.size-1){
Timber.d("得到的所有可下載 uri $newList listSize:${newList.size}")
fragment.saveImageSuccessful(newList)
?.addOnFailureListener {
fragment.saveImageFail(it.toString())
.addOnFailureListener {
fragment.saveImageFail(it.toString())
4.修改saveImageSuccess()
在最上面新增
private var selectedUriList: List<String> = listOf()
因為我們的Firestore不接受Url的格式,所以我們要把它改成String在傳上去!
fun saveImageSuccessful(uriList: List<Uri>){
showSnackBar(resources.getString(R.string.update_pet_image_successful),false)
val list = mutableListOf<String>()
for (element in uriList){
val model = element.toString()
list.add(model)
selectedUriList = list
這樣就完成囉!! 接下來明天將會把它顯示出來!