"不幸的是应用程序停止了#34;当我想将字符串转换为Long时

时间:2016-12-25 09:22:29

标签: android

我正在研究一个关于倒数计时器的非常简单的Android代码,我使用了android CountDownTimer类,所以我想从我的editText中获取millisInFuture(Long),这就是为什么我转换我的从此editText到Long类型(parseLong)的字符串,但是当我尝试运行应用程序时,它停止了。

public class MainActivity extends AppCompatActivity {
TextView tv;
Button btstop;
Button btstart;
EditText et;
Long mnt;
String strmnt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     btstart=(Button) findViewById(R.id.xbtstart);
     btstop=(Button) findViewById(R.id.xbtstop);
     tv=(TextView) findViewById(R.id.xtv);
     et=(EditText) findViewById(R.id.xet);



     try {
        mnt = Long.parseLong(strmnt);
    } catch(NumberFormatException e) {
        System.out.println("parse value is not valid : " + e);
    }

    final countD cdt= new countD(mnt,1000);

    btstart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            cdt.start();
        }
    });

    btstop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            cdt.cancel();
        }
    });

}




public class countD extends CountDownTimer {
    public countD(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onTick(long l) {
        tv.setText("seconds remaining: " + l / 1000);

    }

    @Override
    public void onFinish() {
        tv.setText("done!");

    }
}

}

  I/System.out: parse value is not valid : java.lang.NumberFormatException: Invalid long: "null"

1 个答案:

答案 0 :(得分:1)

将解析部分移到onClick方法中。对输入的值使用一些验证,如下所示。

试试这段代码,

btstart.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String strmnt = et.getText().toString();
        if(strmnt.length() > 0){
             try {
                mnt = Long.parseLong(strmnt);
                final countD cdt= new countD(mnt,1000);
                cdt.start();
            } catch(NumberFormatException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(MainActivity.this, "Please fill the field", Toast.LENGTH_LONG).show();
        }
    }
});