Reputation: 570
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)
}
Upvotes: 0
Views: 3456
Reputation: 1
birthdate.setOnClickListener {
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val datePickerDialog = DatePickerDialog(
this, { view, year, monthOfYear, dayOfMonth ->
val c1 = Calendar.getInstance()
c1.set(year, monthOfYear, dayOfMonth);
val simpleDateFormat = SimpleDateFormat("dd/MM/yyyy")
var strDate = simpleDateFormat.format(c1.time)
birthdate.setText(strDate)
}, year, month, day
)
datePickerDialog.show()
}
<EditText
android:id="@+id/birthdate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"/>
Upvotes: 0
Reputation: 1032
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
Upvotes: 2