Validation for save button - android

I've difficulty in creating a validation before saving it to sqlite, below is the code:
public void save(View v){
String weight = weightinputid.getText().toString();
String bmi = BMIfinal.getText().toString();
String status = BMIStatus.getText().toString();
long id = data.insertData(weight, bmi, status);
if(id<0){
message.mess(this, "Error");
}
else{
message.mess(this, "BMI has been saved");
}
}
How do I create a validation if all the textfields are empty? my problem right now, even if i pressed the save button, the empty textfields was saved inside the database

You can just try this, to check if value is not entered in the EditText.
if (weight .equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value1", Toast.LENGTH_LONG).show();
}
if (bmi.equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value2", Toast.LENGTH_LONG).show();
}
if (status.equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value3", Toast.LENGTH_LONG).show();
}
Alternatively, you can use .matches("") instead of .equals("")
UPDATE
As #Rajesh mentioned in his comments, you can also use
TextUtils.isEmpty(weightinputid.getText())
to achieve the same functionality.

You can definitely do #Lal suggestion but in case the N fields are empty it's going to show the N toasts, and that's not very useful:
I'll suggest to do the following one of the following options:
a) Implement MaterialEditText:
Check the details here:
https://github.com/rengwuxian/MaterialEditText
<com.rengwuxian.materialedittext.MaterialEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Min Characters"
app:met_minCharacters="1" />
b) Use a TextWatcher and enable the SaveButton only after you have your required fields with values:
http://developer.android.com/reference/android/text/TextWatcher.html
You can see how to it with the following question:
Disable Button when Edit Text Fields empty

Related

Android Edittext: when contains misspelling word (with red underline over it), do not allow to submit

I am recently making my first Android App and it has a Edittext area which plans to only allow users to input correctly spelled words. Basically I have already learned how to use layout properties such as Android:inputType to detect any misspelled words. Any misspelled words should be marked with a red underline. But I cannot find a way to prevent users from inputting misspelled words.
The ideal situation is: if a user has input any misspelled words and clicks the submit button, a prompt message (for example a Toast message) would appear to inform the user to modify misspelled words before they can really submit.
Follow steps from this link to create a spelling checker.
http://www.tutorialspoint.com/android/android_spelling_checker.htm
Then modify the sample code above to meet your requirement:
E.g. When (arg0.length == 0), that means there is no suggestion (no spelling mistake), you can create validation from here.
However, it could be a word that is not written in English. So you would need a language detection:
https://code.google.com/p/language-detection/
(From: How to detect language of user entered text?)
What you have to do to achieve this is implement spellchecksession listener.
May be you can use spell check listener along with a text watcher.
SpellCheckListener
You can use this method to validate word(Spell check).
public boolean CheckForWord(String Word){
try {
BufferedReader in = new BufferedReader(new FileReader("/usr/share/dict/american-english"));
String str;
while ((str = in.readLine()) != null) {
if ( str.indexOf( Word) != -1 ) {
return true;
}
}
in.close();
}
catch (IOException e) {
}
return false;
}
And on SUBMIT Button Click
btnSUBMIT.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String EdittextValue = edittext.getText().toString();
if(CheckForWord(EdittextValue)){
Toast.makeText(getActivity(),
"Correct Word " + EdittextValue ,
Toast.LENGTH_LONG).show();
// Do something here.
}
else{
Toast.makeText(getActivity(),
"Wrong Word " + EdittextValue ,
Toast.LENGTH_LONG).show();
}
}
});

Edittext Validation error message in android?

In my app i usually show validation error msg like follow :
if(someString.equals("")){
editText.setError("UserName Should not be blank");
}
is there other way to show error message??
i need your suggestion
I think the way you are showing the error message is better than toast. Sometimes toast duration is too short and the user isn't able to see that.
You can also achieve it by doing this:
EditText et11 = (EditText)findViewById(R.id.username);
if(et11.getText().toString().isEmpty())
{
et11.setError("UserName Should not be blank");
}
private EditText edt_firstName;
private String firstName;
firstName = edt_firstName.getText().toString().trim();
private void validateData(){
firstName = edt_firstName.getText().toString().trim();
if (!firstName.isEmpty(){
//here api call for the login or any other...
} else {
if (firstName.isEmpty()) {
edt_firstName.setError("Please Enter First Name");
edt_firstName.requestFocus();
}
}
}

How to return a toast to anything typed on EditText but a specific word?

I am currently developing my first android application, which is actually my first contact with java ever. Therefore, I suppose this question has an obvious answer to experienced developers, but I couldn't find anything at SO or anywhere else. The following EditText has two toasts (I'm not sure if that sounded right). One is shown if the user types a specific word (in this case, Please is shown if the user types Magic word and presses the button). I would like the another toast to appear if the user types anything else but that word (anything but "Magic word") when clicking the button.
EditText editText1 = (EditText) findViewById(R.id.editText1);
{
if(editText1.getText().toString().trim().equals("Magic word"))
{
Toast.makeText(MainActivity.this,
"Please", Toast.LENGTH_LONG).show();
}
}
else if (editText1.getText().toString().trim().equals())
{
Toast.makeText(MainActivity.this,
"You didn't say the magic word", Toast.LENGTH_LONG).show();
}
}
}
});
I apologize for my poor english. Hopefully, I made myself understood.
Thank you very much.
Following code give you the solution:
final EditText editText1=(EditText)findViewById(R.id.editText1);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
final String edittext=editText1.getText().toString();
if(edittext.trim().equals("Magic word"))
{
Toast.makeText(MainActivity.this,
"Please", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this,
"You didn't say the magic word", Toast.LENGTH_LONG).show();
}
}
});
More simple way!!
String hello = editText1.getText().toString();
and then,
Toast.makeText(MainActivity.this, "The text is" +hello , Toast.LENGTH_SHORT).show();
More accurately "Magic word" isn't a word, its two with a space. The first if statement will require the text in the EditText to be exactly that for the statement to be true. If you actually intended for "magic word" to merely be somewhere in the text typed into the EditText to show a Toast that says please, look into using String.contains() or regex for the first comparison.
For all other conditions there's no need to check the value of the EditText. In other words remove the second if just keep else as Luksprog mentioned.

where to put checking edittext syntax?

i need a favor.. i'm confused to put these codes to check whether the edittext is empty or not:
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
where must i write these codes? is it between these codes?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuawal);
...
...
...
JmlAhliWarisAnakLK = (EditText) findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
or in this function after double sisa=0;??
public void cc() {
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
int JmlWarisAnakLK = Integer.parseInt(JmlAhliWarisAnakLK.getText().toString());
int JmlHarta = Integer.parseInt(JmlHartaPeninggalan.getText().toString());
double HasilSuami = 0;
double HasilIstri = 0;
double HasilAnakLK = 0;
double HasilAnakPR = 0;
double sisa = 0;
}
please correct me if i'm wrong.. :D
you are on the right track
After you set the layout using setContentView you need to add your EditText's which you are doing fine as follows.
JmlAhliWarisAnakLK = (EditText)findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
You then need to store the value you get from the EditText's in some variable,
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
....
....
After you have stored your values you can then call some method that validates your input on click of a button(if you have):
public void validateinput()
{
if(input == null || input.trim().equals(""))
{
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
}
According to me, you should put the check on some event, like if its login screen, then on click of submit button. or other wise on focus change it main instantly provide user with the toast that he left the field empty. or if other case, please provide more information for your query. thanks.
That depends on when you want to validate the editText..You propably have some button which "submits" the EditText so call this code in after onClick event gets fired on the button..
Put the input validation code when you have to navigate away from the current activity, either to go to another activity or to save the input details. That's the least annoying place to shove an error message onto the user.
Another approach is to validate when the focus leaves the EditText. But in this case the error notification should be more subtle (and therefore less annoying) like changing the EditText's background to lightred.
Ur questions does not seem to be clear. Are u asking where do u need to put the validation for empty edittext? If this is ur question then the general case would be to validate during any events such as BUTTON CLICK. Set the onClickListener for ur button and inside ur onclick perform the validation.
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
Your above code is pretty much correct. You Must need to add above code whenever you want to take input from these edittext, Or whenever you want to save these value. make a function which will return true if edit text is empty so u can ask user to enter values
public boolean isETEmpty(){
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
return true;
}
return false; // if not empty
}
call this function Whenever u want to use values from ET, if this function return true, you must let user enter values. Such as on Button Click to save etc

Using a != statement with an edittext object in java?

Im trying to create a button which when pushed reads the edittext box to
Make sure its not blank
Make sure its not the default text in this case "First Name".
However when the button is pushed it still preforms the action even if the edittext text is First Name or blank. Is there an easier way to do this? Also the toast are not made when the text is First Name or blank.
createp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (fname.getText().toString() != "")
if (fname.getText().toString() != "First Name"){
prefsEditor.putInt("user", 1);
prefsEditor.commit();
}
if (fname.getText().toString() == "")
{
Toast.makeText(createactivity.this, "You need a first name to create a profile!",
Toast.LENGTH_LONG).show();
}
if (fname.getText().toString() == "First Name") {
Toast.makeText(createactivity.this, "You need a first name to create a profile!",
Toast.LENGTH_LONG).show();
}
}});
}
Try this instead:
if (!fname.getText().toString().equals(""))
...
Another example:
if (fname.getText().toString().equals("First Name"))
....

Categories

Resources