Steven Steven -4 years ago 237
Android Question

Datepicker in View.Onclicklistener

I'm trying to setup my date picker in a separate class basically to keep my code clean. My code works when using it on a activity but when I attempt to use it on View.OnclickListener I can't seem to get the context right and I receive a context.getsystemservice error. Can you spot what I'm doing wrong?

View.onclicklistener

public class SelectDate extends Activity implements View.OnClickListener {


public Context context;
public EditText selectDate;
public SelectDate(EditText selectDate) {
this.selectDate = selectDate;
}




int year_x, month_x, day_x;
int dateInt;
DatePickerDialog dialog;


@Override
public void onClick(View v) {

InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(selectDate.getWindowToken(), 0);


dialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

year_x = year;
month_x = monthOfYear;
day_x = dayOfMonth;

int month = monthOfYear + 1;
String date = dayOfMonth + "";
if (date.length() == 1)
date = "0" + date;
date = month + date;




selectDate.setText(dayOfMonth + "/" + month + "/" + year);
dateInt = Integer.parseInt(date);

}
}


,year_x,month_x,day_x);

// Disable dates in the past
dialog.getDatePicker().

setMinDate(System.currentTimeMillis()-1000);


dialog.show();

}


}


Setting the onclick listener

EditText selectDate = (EditText)convertView.findViewById(R.id.editDate);
convertView.findViewById(R.id.editDate).setOnClickListener(new SelectDate(selectDate));


Error message

android.content.Context.getSystemService(java.lang.String)' on a null object reference

Answer Source

It is always the best approach to use the View object available to you.

InputMethodManager im = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download