public class TimePickerClass extends Activity{
public TimePicker mTimePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_picker_class);
Button saveTimeButton;
mTimePicker = (TimePicker) findViewById(R.id.timePicker);
mTimePicker.setIs24HourView(true);
saveTimeButton = (Button) findViewById(R.id.next_button);
saveTimeButton.setOnClickListener(v -> {
getTime();
});
public String getTime(){
//TODO
int hour;
int minute;
hour = mTimePicker.getHour();
minute = mTimePicker.getMinute();
String message;
message = "Time:" + hour +" : " + minute;
return message;
}
你好!我有一个类,其中使用TimePicker获取用户选择的时间。我正在尝试这样做:
TimePickerClass time = new TimePickerClass();
String userTime = time.getTime();
但是这不起作用,应用程序已关闭。那如何实现呢?错误如下:
FATAL EXCEPTION: main
Process: com.gfc.glanceclock, PID: 32256
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.TimePicker.getHour()' on a null object reference
答案 0 :(得分:1)
您正在尝试自己创建活动,这就是为什么未调用必要的生命周期方法而您获得NullPointerException
的原因。
如果您想从TimePickerClass活动中获取时间,请启动它以获取结果,例如:
Intent intent = new Intent(context, TimePickerClass.class)
startActivityForResult(intent, REQUEST_CODE)
以及您的TimePickerClass活动中的设置结果:
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Intent intent = new Intent();
intent.putExtra("time", time.getTime());
setResult(RESULT_OK, intent);
finish();
}
});
然后您可以处理结果
protected void onActivityResult(int requestCode, int resultCode, Intent data)
方法。
您可以详细了解here。
答案 1 :(得分:0)
您需要使用setOnTimeChangedListener()
来实现此目的:-
当您尝试使用button
click事件调用计时器方法时,计时器将获得NullPointerException
。
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
getTime();
}
});