Android – Show error in EditText

By -

Problem: How to show error/alert for some cases in EditText?

Description:
Consider a case that we are supposed to collect information from users by filling EditText box and user leaves EditText blank, at that we display alert/error message “Please enter string”. But here is a best way to display alert/error message in EditText for the same case and also for other case.

Solution:
We can display error message in EditText by using setError() method.

android setError
Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	android:id="@+id/linearLayout1"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:orientation="vertical"
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_margin="5dp">

	<EditText
		android:layout_height="wrap_content"
		android:id="@+id/editText1"
		android:layout_width="fill_parent">
	</EditText>

	 <Button
	 	android:layout_height="wrap_content"
	 	android:id="@+id/button1"
	 	android:text="Check"
	 	android:layout_width="wrap_content"
	 	android:onClick="btnClick">
	 </Button>

</LinearLayout>

MainActivity.java

package com.paresh.edittextseterror;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */

	EditText editText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        editText = (EditText) findViewById(R.id.editText1);
    }

    public void btnClick(View v)
    {
    	if(editText.getText().length()==0)
    	{
        	editText.setError("Field cannot be left blank.");
    	}
    }
}

Download this example: Android – Show error in EditText

Paresh Mayani

Lazy android developer, exploring the horizon of android development since 5 years. He is Senior Software engineer at InfoStretch Solutions Pvt. Ltd. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

Loading Facebook Comments ...
Loading Disqus Comments ...