Android - 天文台启动和停止

时间:2017-07-06 13:50:07

标签: android

我想创建一个天文台,我可以用一个按钮开始和停止。使用下面的代码,我只得到一个nullpointer异常。如何避免它,或者将两个功能设置为按钮?

public class MainActivity extends ActionBarActivity {
  Chronometer focus;
  Button start, stop, reset;
  long timeElapsed = SystemClock.elapsedRealtime() - focus.getBase();
  int x;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timeElapsed = x;
    start = (Button) findViewById(R.id.button1);       
    focus = (Chronometer) findViewById(R.id.chronometer1);

    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(x == 0){
            focus.start();
            }

            if(x != 0){
            focus.stop();    
            }
        }
    });

}

}

2 个答案:

答案 0 :(得分:1)

您的代码存在问题:

long timeElapsed = SystemClock.elapsedRealtime() - focus.getBase();

由于焦点变量尚未初始化,因此您将获得NullPointer。 你应该在初始化之后调用getBase()。

此外,您应该为此应用程序使用ToggleButton而不是Button。

答案 1 :(得分:1)

您在初始化之前使用变量。 'focus'和'x'在初始化之前使用。请改用此代码以避免nullpointer异常:

     public class MainActivity extends ActionBarActivity {
  Chronometer focus;
  Button start, stop, reset;
  long timeElapsed = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    start = (Button) findViewById(R.id.button1);       
    focus = (Chronometer) findViewById(R.id.chronometer1);
    // to get the elapsed time use setonChronometerTickListener
    focus.setOnChronometerTickListener(new OnChronometerTickListener() {
         @Override
         public void onChronometerTick(Chronometer chronometer) {
             timeElapsed = SystemClock.elapsedRealtime() - focus.getBase();
         }
    });
    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(timeElapsed == 0){
            focus.setBase(SystemClock.elapsedRealtime());
            focus.start();
            }

            if(timeElapsed != 0){
        timeElapsed = 0;
            focus.stop();    
            }
        }
    });

}