Firestore Kotlin Android中Collection.add()异常排查求助
add() Exception in Kotlin First things first: Check your Logcat for the exact exception message from the Add Doc Failed logs. That will give you the most precise clue, but let's cover the most common culprits and fixes anyway:
1. Firestore Security Rules Blocking the Write
This is the #1 reason for write failures when you're starting out. By default, Firestore's security rules reject all unauthenticated requests.
- Check your rules: Head to the Firebase Console → Firestore Database → Rules tab.
- Temporary development fix: Update rules to allow writes (never leave this in production!):
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if request.auth != null; // Use `if true;` for full open access (unsafe) } } } - Production fix: Set up proper user authentication and restrict writes to only authorized users matching your app's requirements.
2. Settlement Object Serialization Issues
Firestore needs to convert your settlement object into a Firestore document, and it fails if the class doesn't meet serialization rules:
- Add a no-arg constructor: Kotlin data classes don't include an empty constructor by default if you define parameters. Add one explicitly:
data class Settlement( val amount: Double, val date: Timestamp, // Add your other fields here ) { // Required for Firestore serialization constructor() : this(0.0, Timestamp.now()) } - Avoid unsupported types: Firestore can't serialize custom enums directly (use a converter if needed), cyclic references, or non-primitive types without proper getters/setters.
- Use Firebase annotations: Add
@IgnoreExtraPropertiesto ignore fields Firestore doesn't recognize, or@PropertyNameto map class fields to different document key names.
3. Network Connectivity Problems
Firestore requires an active network for writes unless you've enabled offline persistence.
- Verify device network: Make sure your emulator/physical device has a working internet connection.
- Enable offline persistence: Add this when initializing Firestore (works for Android):
With persistence enabled, writes will queue locally and sync automatically once the network returns.val db = FirebaseFirestore.getInstance() try { db.enablePersistence() } catch (e: FirebaseFirestoreException) { // Handle cases where persistence can't be enabled (e.g., multiple Firestore instances) }
4. Invalid Field Values or Document Size Limits
Firestore enforces strict limits on what you can store:
- Document size cap: Max 1MB per document. If your
settlementincludes large data (like base64-encoded files), trim it down or store it in Cloud Storage instead. - Field value restrictions: Strings can't exceed 1MB, numbers must be valid (no NaN/Infinity), and timestamps must fall within Firestore's supported range (roughly 1970–2100).
- Check for null edge cases: While Firestore supports nulls, some rule configurations might block writes with null values in required fields.
5. Outdated or Conflicting Firebase SDKs
Old SDK versions often have bugs that cause serialization or network issues.
- Update Firestore SDK: In your app-level
build.gradle(module level), use the latest stable version:dependencies { implementation 'com.google.firebase:firebase-firestore:24.10.0' // Check Firebase docs for the latest version implementation 'com.google.firebase:firebase-auth:22.3.0' // Include if you use authentication } - Resolve conflicts: Run
./gradlew app:dependenciesto check for conflicting library versions and adjust your dependencies accordingly.
Bonus: Improve Error Logging
Your current code logs the exception, but adding the exception message will help you debug faster:
.addOnFailureListener({ e -> Log.w("Add Doc Failed", "Error adding document: ${e.message}", e) })
内容的提问来源于stack exchange,提问作者jitain sharma

