-2

I am displaying a date in a TextView. It is all working fine when there is some date. But if no date is chosen or if the TextView is empty (there is a hint "dd-mm-yyyy" though) then the app crashes. I am checking for empty TextView as follows: if(textview.setText().toString().isEmpty()) {//show error} can anyone help what I am doing wrong?

Initialisation of TextView and TextInputlayout:

tv_Current_Date = (TextView) findViewById(R.id.tv_Current_Date);
til_Current_Date = (TextInputLayout) findViewById(R.id.til_Current_Date);

Here is the code responsible for crash:

if (tv_Current_Date.getText().toString().isEmpty()) {
    til_Current_Date.setError("Please choose a date");
}

Method to set date:

public void setCurrentDateOnView() {
    String dateFormat = "dd-MM-yyyy";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
    tv_Current_Date = (TextView) findViewById(R.id.tv_Current_Date);
    tv_Current_Date.setText(simpleDateFormat.format(calendar_now.getTime()));
    String short_weekday = new DateFormatSymbols().getShortWeekdays()[day_of_current_week];
    tv_Current_weekday.setText(short_weekday);
}
Valentin Michalak
  • 2,089
  • 1
  • 14
  • 27
Cjsparrow
  • 59
  • 2
  • 2
  • 9

4 Answers4

6

try this

if (tv_Current_Date.getText().toString().equals("")) {
      til_Current_Date.setError("Please choose a date");
}
joao86
  • 2,056
  • 1
  • 21
  • 23
  • 1
    Thanks for your cooperation. Actually the problem was to initialize the TextView. Now I have corrected it, and my code is working fine – Cjsparrow Sep 09 '17 at 16:38
0

Try this

if(tv_Current_Date.getText().toString().equals("") && tv_Current_Date.getText().length() <= 0){
   tv_Current_Date.setError("your message");
}
Tejas
  • 358
  • 5
  • 23
  • Thanks for your cooperation. Actually the problem was to initialize the TextView. Now I have corrected it, and my code is working fine. – Cjsparrow Sep 09 '17 at 16:37
0

On top of what Tejas and joao86 said, you should check and validate that the input is actually a date.

Check the following links where they discuss about validation:

Date Validation in Android

How to validate date in dd/mm/yyyy format in editext in android?

Java: Check the date format of current string is according to required format or not

user2399432
  • 738
  • 1
  • 9
  • 17
0

You need an else condition besides an if condition to run your code.

if (tv_Current_Date.getText().toString().isEmpty()) {
                til_Current_Date.setError("Please choose a date");
            } else{ put the code here}
Haseeb Khan
  • 127
  • 2
  • 9