architecture-samples icon indicating copy to clipboard operation
architecture-samples copied to clipboard

[dev-todo-mvvm-live-kotlin] App crashes when adding task with empty title or description

Open rzeznix opened this issue 7 years ago • 1 comments

saveTask() function of AddEditTaskViewModel.kt is calling Task(title.get(), description.get()) which causes crash when adding new task with title or description being empty.

rzeznix avatar Feb 22 '18 11:02 rzeznix

the crash happens because in the dev-todo-mvvm-live-kotlin branch the ViewModel’s saveTask() is doing something like:

fun saveTask() { val task = Task(title.get(), description.get()) // <- boom if null ... } Here, title and description are probably ObservableField<String> values bound to EditTexts. If the user hasn’t typed anything, get() returns null, which violates Task’s constructor requirements (likely non-null String) and leads to a NullPointerException.

Why it crashes In Kotlin, if Task’s constructor is defined as:

data class Task( val title: String, val description: String, ... ) then passing a null from title.get() or description.get() will crash at runtime because Kotlin’s non-null parameters can’t be null.

How to fix it The fix is to handle null or empty cases before constructing the Task.

Option 1 – Use default empty strings

fun saveTask() { val currentTitle = title.get()?.trim().orEmpty() val currentDescription = description.get()?.trim().orEmpty()

if (currentTitle.isEmpty() && currentDescription.isEmpty()) {
    // Show an error message via LiveData
    _snackbarText.value = R.string.empty_task_message
    return
}

val task = Task(currentTitle, currentDescription)
...

} Option 2 – Prevent saving empty tasks altogether If the app shouldn’t allow empty titles or descriptions:

fun saveTask() { val currentTitle = title.get()?.trim() val currentDescription = description.get()?.trim()

if (currentTitle.isNullOrEmpty() || currentDescription.isNullOrEmpty()) {
    _snackbarText.value = R.string.empty_task_message
    return
}

val task = Task(currentTitle, currentDescription)
...

} Option 3 – Change Task to accept nullable values Not really recommended here, because the Task model should represent a valid, saved entity, not a partially empty one.

Why the original code didn’t guard against null The original MVVM sample assumes the binding layer or XML input validation ensures non-null values, but in practice, data binding ObservableField can still be null unless you initialize it and trim input before use.

VaradGupta23 avatar Aug 08 '25 12:08 VaradGupta23