0

我有一个 24 小时格式的 timePicker,我想获取结果,将它们放入变量中,另外使用变量,然后在 textView 中显示它们。Eclipse 没有给我和语法错误,但是当我运行应用程序时,它在我启动“DisplayMessageActivity.java”时崩溃。

这是代码:

package com.example.sleepytime;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

@SuppressLint("NewApi")
public class DisplayMessageActivity extends Activity {

 TimePicker timepicker;
 public int hour1 = timepicker.getCurrentHour();
 public int min1 = timepicker.getCurrentMinute();


@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);
    // Show the Up button in the action bar. 
    getActionBar().setDisplayHomeAsUpEnabled(true);

    timepicker = (TimePicker) findViewById(R.id.timePicker1);
    timepicker.setIs24HourView(true);

    Button mButton = (Button) findViewById(R.id.button1);
    mButton.setOnClickListener(new View.OnClickListener() { 
        public void onClick(View printIt) {
        final TextView mTextView = (TextView) findViewById(R.id.print);
        mTextView.setText(hour1 + min1);
}   

}); 

}

}

4

2 回答 2

1

这里

public int hour1 = timepicker.getCurrentHour();
public int min1 = timepicker.getCurrentMinute();

timepickernull。你需要把它onCreate()像这里

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);
    // Show the Up button in the action bar. 
    getActionBar().setDisplayHomeAsUpEnabled(true);

timepicker = (TimePicker) findViewById(R.id.timePicker1);
timepicker.setIs24HourView(true);
hour1 = timepicker.getCurrentHour();
min1 = timepicker.getCurrentMinute();

和改变

public int hour1 = timepicker.getCurrentHour();
public int min1 = timepicker.getCurrentMinute();

public int hour1;
public int min1;

这是我看到的第一个问题。可能还有更多,但这将使您无法继续前进。

 mButton.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View printIt) {
    final TextView mTextView = (TextView) findViewById(R.id.print);
    String hourString = String.valueOf(hour);
    String minString = String.valueOf(minute);
    mTextView.setText(hourString + minString);
于 2013-03-24T20:29:45.487 回答
0
TimePicker timepicker;
 public int hour1 = timepicker.getCurrentHour();
 public int min1 = timepicker.getCurrentMinute();

你不能这样做,它会给你空指针异常,这样做

timepicker = (TimePicker) findViewById(R.id.timePicker1);
timepicker.setIs24HourView(true);
hour1 = timepicker.getCurrentHour();
min1 = timepicker.getCurrentMinute();

另外,在低于 3.0 的 api 上运行时,您当前的代码会中断。请检查 getActionBar().setDisplayHomeAsUpEnabled(true);

或者如果您不想支持蜂窝之前的版本,请将最低 sdk 更改为 3.0

于 2013-03-24T20:34:02.480 回答