简体   繁体   中英

How to set Text for EditText with Date Picker in Kotlin

I am new to Kotlin and android app development.

I am following a online course and one of the exercises is picking date to remind a to do item at certain time.

What i did is created EditText and implemented DatePicker. When user clicks date picker is opened and after I select the date, I can not set to text of EditText.

BTW I already checked other related questions and it says check your id to make sure you are referring to non null widget in correct layout file. I double checked it and it is not the problem

Here is the error.

Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference

//EditText on layout file
<EditText
    android:id="@+id/calendarEditText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:hint="Select your date"
    android:focusable="false"
/>

//My Kotlin code
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add)

    //DatePicker is called inside onCreate function
    calendarEditText.setOnClickListener {
        val newFragment = DatePickerFragment()
        newFragment.show(supportFragmentManager, "datePicker")
    }
}
// DateSet part of my DatePickerFragment
override fun onDateSet(view: DatePicker, year: Int, month: Int, dayOfMonth: Int) {

    //selected date converted into one string
    val date = "$year/$month/$dayOfMonth"

    //this is where I got the error
    calendarEditText.setText(date)
}

for me calendarEditText is null because you call it in a DatePickerFragment, so you are in a different context.

In your onDataSet, update edittext like that :

((MyActivity) activity).setEdt(date);

and in your activity, something like that :

public setEdt(date: String): void {
calendarEditText.setText(date)
}

or follow this tuto to avoid fragment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM