试图通过添加变量创建一个简单的应用程序,遇到一些问题

时间:2013-03-24 19:56:09

标签: java android eclipse timepicker addition

我有一个24h格式的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);
}   

}); 

}

}

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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();

另外,当你在api低于3.0的情况下运行时,你当前的代码会中断。检查  getActionBar()setDisplayHomeAsUpEnabled(真);

如果您不想支持蜂窝之前的版本

,请将最小sdk更改为3.0