I have an AppCompatSpinner
and I'm trying to set a text on a TextView
here.
Here's my code:
eSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
final TextView eSpinnerTV = (TextView) adapterView.getSelectedView();
switch (i) {
case 0:
final Calendar c = Calendar.getInstance();
mHourEnd = c.get(Calendar.HOUR_OF_DAY);
mMinuteEnd = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(activityName.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
Calendar date = Calendar.getInstance();
date.set(Calendar.HOUR_OF_DAY, hourOfDay);
date.set(Calendar.MINUTE, minute);
date.set(Calendar.AM_PM, date.get(Calendar.AM_PM));
sEnd(hourOfDay, minute);
uTimeInSF = new SimpleDateFormat("HH:mm:ss").format(date.getTime());
eString = new SimpleDateFormat("hh:mm a").format(date.getTime());
// error on the line below
eSpinnerTV.setText(uTimeAMPM);
}
}, mHourEnd, mMinuteEnd, false);
timePickerDialog.show();
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Here's sEnd.java
file's code:
public void sEnd(int hour, int min) {
if (hour == 0) {
hour += 12;
format = "AM";
} else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
uTimeAMPM = hour + ":" + min + " " + format;
}
Here's the xml
code:
<android.support.v7.widget.AppCompatSpinner
android:id="@+id/pTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:entries="@array/pTimeList"
style="@style/Base.Widget.AppCompat.Spinner">
</android.support.v7.widget.AppCompatSpinner>
Here's pTimeList
:
<string-array name="pTimeList">
<item>Pick a time..</item>
</string-array>
As soon as I'm clicking the OK
button after choosing time from TimePickerDialog
, the app is crashing giving this error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
on the line specified in the code above.
What is causing this error even when this textview has been clearly reference above in the code as final TextView eSpinnerTV = (TextView) adapterView.getSelectedView();
?
Please let me know.