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

CEO & Co-Founder at SolGuruz® | Organiser @ GDG Ahmedabad | Top 0.1% over StackOverflow | 15+ years experienced Tech Consultant | Helping startups with Custom Software Development

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