Giới thiệu
Bài viết minh họa cách dùng String.isEmpty() (Kotlin) hoặc TextUtils.isEmpty() (Java/Android) để kiểm tra chuỗi rỗng hoặc null trước khi xử lý.
Các bước thực hiện
Bước 1: Tạo project mới
Android Studio → File → New Project → Empty Activity.
Bước 2: Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">
<EditText
android:id="@+id/etInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Nhập tên (ví dụ: Krishna sai)"
android:inputType="textCapWords" />
<Button
android:id="@+id/btnCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Kiểm tra & Tìm 'sai'" />
<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
Bước 3: Logic (MainActivity.kt)
package com.example.isemptydemo
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnCheck.setOnClickListener {
val input = etInput.text.toString()
// Kiểm tra rỗng (Kotlin: isEmpty() trên String không null)
// Note: EditText.text không bao giờ null, nhưng toString() có thể ""
if (input.isEmpty()) {
etInput.error = "Vui lòng nhập tên"
tvResult.text = "Chuỗi rỗng"
return@setOnClickListener
}
// Tìm vị trí substring "sai"
val index = input.indexOf("sai")
val result = if (index >= 0) "Tìm thấy 'sai' tại index $index" else "Không tìm thấy 'sai'"
tvResult.text = "Chuỗi: '$input' (độ dài ${input.length})\n$result"
Toast.makeText(this, result, Toast.LENGTH_LONG).show()
}
}
}
Các cách kiểm tra rỗng/Null trên Android
| Phương pháp | Null safe | Trim whitespace | Ghi chú |
|---|---|---|---|
str.isEmpty() (Kotlin) |
❌ (NPE nếu str null) | ❌ | Chỉ cho non-null String |
str.isNullOrEmpty() (Kotlin) |
✅ | ❌ | Khuyên dùng cho nullable String |
str.isBlank() (Kotlin 1.3+) |
❌ | ✅ (chỉ whitespace) | True nếu rỗng hoặc chỉ space/tab/newline |
str.isNullOrBlank() (Kotlin) |
✅ | ✅ | ✅ **Khuyên dùng nhất** cho input user |
TextUtils.isEmpty(str) (Java/Android) |
✅ | ❌ | Null hoặc length==0 |
TextUtils.isBlank(str) (API 29+) |
✅ | ✅ | Null, rỗng, hoặc chỉ whitespace |
Best Practice cho EditText Input
val input = etInput.text.toString()
// Cách 1: Chỉ check rỗng
if (input.isEmpty()) { error }
// Cách 2: Check rỗng + chỉ khoảng trắng (KHUYẾN NGHỊ)
if (input.isBlank()) { error }
// Cách 3: Null-safe (nếu input có thể null)
val inputNullable: String? = etInput.text?.toString()
if (inputNullable.isNullOrBlank()) { error }
Ví dụ kết hợp: Validate form
fun validateForm(): Boolean {
val name = etName.text.toString()
val email = etEmail.text.toString()
val phone = etPhone.text.toString()
return if (name.isBlank()) {
etName.error = "Tên không được để trống"
false
} else if (email.isBlank() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
etEmail.error = "Email không hợp lệ"
false
} else if (phone.isBlank() || phone.length < 10) {
etPhone.error = "Số điện thoại không hợp lệ"
false
} else {
true
}
}
Lưu ý
EditText.textlàEditable(không null),.toString()trả về String (có thể "").isBlank()tốt hơnisEmpty()vì user có thể nhập space.- Luôn trim() trước khi validate logic nghiệp vụ:
val clean = input.trim(). - Kotlin:
if (input.isNullOrBlank()) returnguard clause gọn gàng.