이 튜토리얼에서는 안드로이드에서 isEmpty() 메서드를 활용해 EditText에 입력된 값이 비어 있는지 확인하고, 그 결과를 TextView에 표시하는 방법을 단계별로 살펴봅니다. 입력값 검증은 사용자 경험과 데이터 무결성을 위해 반드시 필요한 과정입니다.
1단계: 새 프로젝트 생성
Android Studio에서 File ⇒ New Project로 이동하여 새 프로젝트를 생성하고, 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.
2단계: 레이아웃 XML 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Enter name"
android:layout_height="wrap_content" />
<Button
android:id="@+id/click"
android:text="Click"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:textSize="25sp"
android:layout_height="wrap_content" />
</LinearLayout>
위 코드에서는 이름을 입력받는 EditText, 클릭용 Button, 결과를 표시할 TextView를 수직 LinearLayout으로 배치했습니다. 사용자가 버튼을 클릭하면 입력된 데이터를 가져와 해당 값이 비어 있는지 여부를 확인하게 됩니다.
3단계: MainActivity 자바 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
button = findViewById(R.id.click);
text = findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty()) {
if (name.getText().toString().length() >= 0) {
int index = name.getText().toString().indexOf("sai");
text.setText(String.valueOf(index));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}
여기서 핵심은 name.getText().toString().isEmpty() 부분입니다. isEmpty()는 문자열의 길이가 0일 때 true를 반환하므로, 입력값이 비어 있는지 검사하는 가장 간결하고 안전한 방법입니다. 값이 존재하면 입력 문자열에서 "sai"가 시작되는 인덱스를 찾아 TextView에 출력하고, 비어 있다면 setError()를 통해 오류 메시지를 표시합니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택합니다. 그러면 기기 화면에 아래와 같은 기본 화면이 나타납니다.

위 결과에서 "Krishna sai"라는 문자열을 입력하면 빈 문자열이 아니므로 isEmpty() 검사를 통과하고, "sai"가 시작되는 인덱스인 8이 계산되어 화면에 표시됩니다.
참고 사항
예제 코드는 구버전 support 라이브러리(android.support.v7.app.AppCompatActivity)를 기준으로 작성되었지만, 최신 Android Studio 프로젝트에서는 androidx.appcompat.app.AppCompatActivity로 임포트 문을 변경해야 합니다. Kotlin 프로젝트라면 name.text.isNullOrEmpty() 형태로 동일한 로직을 더욱 간결하게 구현할 수 있습니다.