2017-09-04 140 views
-2

我在TextView中顯示日期。有一些日期的時候,它工作正常。但是,如果沒有選擇日期或者TextView爲空(儘管有提示「dd-mm-yyyy」),那麼應用程序會崩潰。我正在檢查空的TextView,如下所示:if(textview.setText()。toString()。isEmpty()){//顯示錯誤}任何人都可以幫助我做錯了什麼? TextView中和TextInputlayout的檢查TextView是否爲空?

初始化:

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

這裏負責崩潰的代碼:

if (tv_Current_Date.getText().toString().isEmpty()) { 
       til_Current_Date.setError("Please choose a 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); 
} 
+0

另外補充,你的情況下,定義til_Current_Date的部分是有你所遇到的問題。 – Juan

+0

你收到了什麼崩潰? –

+0

我編輯了我的代碼@Juan。該應用程序正在停止-an_droid_dev。 – Cjsparrow

回答

1

試試這個

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

感謝您的合作。其實問題是初始化TextView。現在我糾正了它,並且我的代碼工作正常 – Cjsparrow

0

試試這個

if(tv_Current_Date.getText().toString().equals("") && tv_Current_Date.getText().length() <= 0){ 
    tv_Current_Date.setError("your message"); 
} 
+0

感謝您的合作。其實問題是初始化TextView。現在我已經糾正它,並且我的代碼工作正常。 – Cjsparrow