Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Android

एंड्रॉइड में EditText खाली है या नहीं कैसे जांचें?

एंड्रॉइड में EditText खाली/वैलिड है या नहीं जांचना — बेस्ट प्रैक्टिसेज

यूज़र इनपुट वैलिडेट करना हर ऐप की बुनियादी जरूरत है। TextUtils.isEmpty() सबसे सरल तरीका है, लेकिन **सिर्फ खाली स्ट्रिंग ही नहीं, व्हाइटस्पेस-ओनली स्ट्रिंग भी अमान्य माननी चाहिए**। यह ट्यूटोरियल सभी सामान्य पैटर्न कवर करता है।

चरण 1: नया प्रोजेक्ट बनाएं

Android Studio → File → New → New Project → "Empty Activity" → Finish।

चरण 2: 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:padding="24dp"
    android:gravity="center">

    <EditText
        android:id="@+id/etInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="कुछ टाइप करें..."
        android:inputType="text"
        android:layout_marginBottom="16dp"
        android:padding="12dp"
        android:background="@android:drawable/edit_text" />

    <Button
        android:id="@+id/btnCheck"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="जांचें"
        android:padding="12dp 32dp" />

    <TextView
        android:id="@+id/tvResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:textSize="18sp"
        android:text="परिणाम: -" />

</LinearLayout>

चरण 3: MainActivity.java — विभिन्न वैलिडेशन तरीके

package com.example.edittextvalidation;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText etInput;
    private Button btnCheck;
    private TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etInput = findViewById(R.id.etInput);
        btnCheck = findViewById(R.id.btnCheck);
        tvResult = findViewById(R.id.tvResult);

        btnCheck.setOnClickListener(v -> validateInput());
    }

    private void validateInput() {
        String input = etInput.getText().toString();

        // तरीका 1: TextUtils.isEmpty() — null या खाली स्ट्रिंग चेक करता है
        boolean isEmpty1 = TextUtils.isEmpty(input);

        // तरीका 2: trim() + isEmpty() — व्हाइटस्पेस-ओनली भी पकड़ता है
        boolean isEmpty2 = input.trim().isEmpty();

        // तरीका 3: Kotlin एक्सटेंशन (अगर Kotlin उपयोग कर रहे हैं)
        // boolean isEmpty3 = input.isNullOrBlank(); // Kotlin

        // तरीका 4: लंबाई चेक
        boolean isEmpty4 = input.length() == 0;

        // परिणाम दिखाएं
        String result = String.format(
                "मूल: '%s'\n" +
                "TextUtils.isEmpty(): %b\n" +
                "trim().isEmpty(): %b\n" +
                "length()==0: %b",
                input, isEmpty1, isEmpty2, isEmpty4
        );
        tvResult.setText(result);

        // व्यावहारिक वैलिडेशन: trim() के बाद चेक करें
        if (input.trim().isEmpty()) {
            Toast.makeText(this, "❌ फील्ड खाली या केवल स्पेस — मान्य नहीं", Toast.LENGTH_SHORT).show();
            etInput.setError("आवश्यक फील्ड");
            etInput.requestFocus();
        } else {
            Toast.makeText(this, "✅ मान्य इनपुट: " + input.trim(), Toast.LENGTH_SHORT).show();
            etInput.setError(null);
        }
    }
}

चरण 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.edittextvalidation">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.EditTextValidation">

        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

चलाएं और टेस्ट करें

  1. खाली छोड़कर "जांचें" दबाएं — "खाली या केवल स्पेस" टोस्ट, एरर मार्कर।
  2. केवल स्पेस टाइप करके दबाएं — वही परिणाम (trim() की वजह से)।
  3. वास्तविक टेक्स्ट टाइप करके दबाएं — "मान्य इनपुट" टोस्ट।

🔍 वैलिडेशन तरीकों की तुलना

तरीकाकोडnull सेफ?" " (स्पेस) पकड़ता है?सिफारिश
TextUtils.isEmpty()TextUtils.isEmpty(s)✅ हां❌ नहींबेसिक null/empty चेक
trim().isEmpty()s.trim().isEmpty()❌ NPE अगर null✅ हां✅ **सबसे अच्छा सामान्य उपयोग के लिए**
TextUtils.isEmpty(trim())TextUtils.isEmpty(s.trim())✅ हां✅ हांसुरक्षित + व्हाइटस्पेस चेक
Kotlin isNullOrBlank()s.isNullOrBlank()✅ हां✅ हांKotlin में सर्वश्रेष्ठ
length() == 0s.length() == 0❌ NPE❌ नहींनहीं सिफारिश

🎯 उन्नत वैलिडेशन पैटर्न्स

1. ईमेल वैलिडेशन

private boolean isValidEmail(String email) {
    return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

2. फोन नंबर (सिंपल)

private boolean isValidPhone(String phone) {
    return !TextUtils.isEmpty(phone) && phone.length() >= 10 && phone.matches("\\d+");
}

3. पासवर्ड स्ट्रेंथ

private int checkPasswordStrength(String pwd) {
    if (TextUtils.isEmpty(pwd)) return 0;
    int score = 0;
    if (pwd.length() >= 8) score++;
    if (pwd.matches(".*[A-Z].*")) score++;
    if (pwd.matches(".*[a-z].*")) score++;
    if (pwd.matches(".*\\d.*")) score++;
    if (pwd.matches(".*[!@#$%^&*].*")) score++;
    return score; // 0-5
}

4. रियल-टाइम वैलिडेशन (TextWatcher)

etInput.addTextChangedListener(new TextWatcher() {
    @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {
        String input = s.toString();
        if (input.trim().isEmpty()) {
            etInput.setError("आवश्यक");
            btnCheck.setEnabled(false);
        } else {
            etInput.setError(null);
            btnCheck.setEnabled(true);
        }
    }
});

📱 TextInputLayout (Material Components) — बिल्ट-इन एरर UI

<!-- build.gradle -->
implementation 'com.google.android.material:material:1.12.0'

<!-- Layout -->
<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="ईमेल">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress" />

</com.google.android.material.textfield.TextInputLayout>

// कोड में
TextInputLayout tilEmail = findViewById(R.id.tilEmail);
tilEmail.setError("अमान्य ईमेल"); // लाल एरर टेक्स्ट, एनिमेटेड
tilEmail.setErrorEnabled(false); // क्लियर करें

सारांश

  • ✅ **सबसे अच्छा**: input.trim().isEmpty() (null चेक के बाद) या TextUtils.isEmpty(input.trim())
  • ✅ TextUtils.isEmpty() null-सेफ है लेकिन व्हाइटस्पेस नहीं पकड़ता।
  • ✅ et.setError("मैसेज") से बिल्ट-इन एरर UI दिखाएं।
  • 🚀 **Material TextInputLayout** — एनिमेटेड एरर, काउंटर, पासवर्ड टॉगल, हेल्पर टेक्स्ट बिल्ट-इन।
  • 🔄 रियल-टाइम फीडबैक के लिए TextWatcher उपयोग करें।
  1. Android का सिस्टम वर्जन कैसे जांचें? Android का सिस्टम वर्जन कैसे जांचें?

    परिचय यह उदाहरण दर्शाता है कि Android डिवाइस के सिस्टम वर्जन (Android संस्करण नाम और API लेवल) को प्रोग्रामेटिक रूप से कैसे जांचा जाए। चरण 1: नया प्रोजेक्ट बनाएं Android Studio में नया प्रोजेक्ट बनाएं। चरण 2: लेआउट XML res/layout/activity_main.xml: <?xml version=1.0 encoding=utf-8?> <Rela

  1. एंड्रॉयड पर स्क्रीन टाइम कैसे चेक करें एंड्रॉयड पर स्क्रीन टाइम कैसे चेक करें

    स्मार्टफोन हमारे जीवन का इतना बड़ा हिस्सा हैं, लेकिन यह ट्रैक खोना आसान हो सकता है कि हम उन्हें घूरने में कितना समय बिताते हैं। सौभाग्य से, आप Digital Wellbeing ऐप के माध्यम से एंड्रॉयड पर अपना स्क्रीन टाइम चेक कर सकते हैं, जो आपके कुल फोन उपयोग और आप अलग-अलग ऐप्स में कितना समय बिताते हैं, दोनों को

  1. अपने एंड्रॉइड की बैटरी हेल्थ चेक करें: स्टेप-बाय-स्टेप गाइड अपने एंड्रॉइड की बैटरी हेल्थ चेक करें: स्टेप-बाय-स्टेप गाइड

    हमारे आस-पास की ज्यादातर चीजें काम करने के लिए किसी न किसी रूप में बैटरी का उपयोग करती हैं। मोबाइल फोन से लेकर रिमोट कंट्रोल तक, बैटरी हमारे जीवन का अभिन्न अंग बन गई हैं। जब मोबाइल की बात आती है, तो उनकी लिथियम-आयन बैटरी लंबे उपयोग के बाद खराब हो जाती हैं। बैटरी का खराब होना अनिवार्य है और यह अनियमि