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.

Output Snapshot:

Android - Show error setError() demo

Android - Show error setError() demo

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="Test it!!"
	 	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;

/**
 *
 * @author Paresh N. Mayani
 * Purpose: Demo to show the purpose of setError() method in EditText view.
 *
 */
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("please input text");
    	}
    }
}

Download this example: Android – Show error in EditText


 
 
 
 

Paresh Mayani

Paresh Mayani is a lead android developer from India. Currently, He is Sr. Software engineer at InfoStretch Solutions Pvt. Ltd. He has been developing android apps since very 1st version i.e. Android 1.5, he says he has seen days and nights of Android history. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

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