You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将Map存入Firebase Storage及Firestore的Android技术问题求助

Troubleshooting Your Event Creation Flow (Firebase Storage & Firestore Issues)

Hey there, it’s super tricky when your code seems to "work" (since it navigates to Menu.class) but the actual data doesn’t save to Firebase. Let’s break down the key issues and fix them step by step.

Core Problem: Incorrect Download URL Retrieval

The biggest red flag here is how you’re getting the download URL:

String downloadUri = file.getDownloadUrl().toString();

getDownloadUrl() returns a Task<Uri>—it’s an asynchronous operation. Calling toString() on it just gives you the string representation of the Task object, not the actual download URL. This invalid URL is being saved to Firestore, and worse, you’re not handling any failures from this step, so no errors pop up to clue you in.

Step-by-Step Fixes & Troubleshooting

1. Fix the Download URL Fetching

Replace the synchronous toString() call with an asynchronous listener to get the real download URL. This ensures you only proceed once you have a valid URL:

file.putFile(eventImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
        if(task.isSuccessful()){
            // Fetch download URL asynchronously
            file.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    String downloadUri = uri.toString();
                    Map<String, Object> eventsMap = new HashMap<>();
                    eventsMap.put("image_url", downloadUri);
                    eventsMap.put("desc", desc);
                    
                    firebaseFirestore.collection("Events").add(eventsMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
                        @Override
                        public void onComplete(@NonNull Task<DocumentReference> task) {
                            if(task.isSuccessful()){
                                Toast.makeText(newEventActivity.this, "Event Was Created", Toast.LENGTH_LONG).show();
                                Intent intent = new Intent(newEventActivity.this, Menu.class);
                                startActivity(intent);
                                finish();
                            } else {
                                String error = task.getException().getMessage();
                                Toast.makeText(newEventActivity.this, "Firestore Error: " + error , Toast.LENGTH_LONG).show();
                            }
                            newEventProgress.setVisibility(View.INVISIBLE);
                        }
                    });
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    // Handle failure to retrieve download URL
                    Toast.makeText(newEventActivity.this, "Failed to get image URL: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    newEventProgress.setVisibility(View.INVISIBLE);
                }
            });
        } else{
            // Handle image upload failure
            String error = task.getException().getMessage();
            Toast.makeText(newEventActivity.this, "Image Upload Error: " + error, Toast.LENGTH_LONG).show();
            newEventProgress.setVisibility(View.INVISIBLE);
        }
    }
});

2. Add Error Logging for All Steps

You only handled Firestore errors in your original code, but missed errors for:

  • Image upload to Storage
  • Download URL retrieval
    Adding failure listeners to every async step will finally show you what’s going wrong if something breaks, instead of silently failing.

3. Verify Firebase Security Rules

Make sure your Storage and Firestore rules allow write access (use these for testing, then lock them down for production):

  • Firebase Storage Rules:
    rules_version = '2';
    service firebase.storage {
      match /b/{bucket}/o {
        match /event_images/{allPaths=**} {
          allow read, write: if request.auth != null; // Use allow write: true; temporarily for unauthenticated testing
        }
      }
    }
    
  • Firestore Rules:
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /Events/{document} {
          allow read, write: if request.auth != null; // Use allow write: true; temporarily for unauthenticated testing
        }
      }
    }
    

Permission issues are a common culprit for silent failures, so testing with open rules first can rule this out.

4. Validate eventImageUri Before Upload

Add a quick check to confirm the image URI is valid right before uploading:

if(!TextUtils.isEmpty(desc) && eventImageUri != null){
    // Log the URI to verify it points to a valid file
    Log.d("NewEvent", "Image URI: " + eventImageUri.toString());
    newEventProgress.setVisibility(View.VISIBLE);
    // Rest of your code...
}

Check Logcat to ensure the URI looks like a valid file path (e.g., content://media/external/images/media/123 or file:///storage/emulated/0/...).

Why Your Original Code Navigated to Menu.class

Even though the data didn’t save, your code navigates to Menu.class because it only checks if the upload task completed successfully—it doesn’t verify that the download URL was fetched or the Firestore write succeeded. The fix above ensures navigation only happens when all critical steps (upload, URL fetch, Firestore write) are successful.

内容的提问来源于stack exchange,提问作者Martynas Krupskis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:21:22