java - 当我把它放在 try 块中时按钮不起作用
问题描述
我正在开发一个应用程序,我进入了这个:
第一活动:
EditText inputCorrect = findViewById(R.id.inputCorrect);
Button calcButton = findViewById(R.id.calculateButton);
try {
int correctAmount = Integer.parseInt(inputCorrect.getText().toString());
Intent resultPage = new Intent(getApplicationContext(),resultActivity.class);
resultPage.putExtra("c_a",correctAmount);
calcButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(resultPage);
}
});
} catch (NumberFormatException nfe) {
}
第二活动:
Bundle myIntent = getIntent().getExtras();
int value =myIntent.getInt("c_a");
我想通过这些活动传递一个 int,但是当我按下按钮时它不起作用。
如果我将按钮无效try{ }
,它不会检测到resultPage
。
有任何想法吗?太感谢了。
解决方案
试试这个代码,它对我有用。
public class TestButtonNotWork extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_button_not_work);
EditText inputCorrect = findViewById(R.id.inputCorrect);
Button calcButton = findViewById(R.id.calculateButton);
Log.d("TestButtonNotWork", "TANCOLO===> init views ");
calcButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
int correctAmount = Integer.parseInt(inputCorrect.getText().toString());
Log.d("TestButtonNotWork", "TANCOLO===> init views, correctAmount = " + correctAmount);
Intent resultPage = new Intent(getApplicationContext(), ResultActivity.class);
resultPage.putExtra("c_a", correctAmount);
Log.d("TestButtonNotWork", "TANCOLO===> start ResultActivity");
startActivity(resultPage);
} catch (Exception exception) {
Log.d("TestButtonNotWork", "TANCOLO===> exception = " + exception);
}
}
});
}
}
注意: Integer.parseInt()
必须使用try .. catch
,否则会崩溃
推荐阅读
- c++ - 使用带有嵌套循环的 OpenMP 缩减子句
- recursion - 有没有不支持递归的现代语言?
- google-api - 此应用程序未经 Google 验证,即使已验证
- c# - 制作一个全局变量 int
- javascript - JavaScript - 循环函数
- outlook - Outlook 预选发件人
- ruby-on-rails - Rails 使用来自不同 activerecord 模型的列作为外键
- java - lambda 表达式处的 NULLPOINTER
- triggers - 如果联系人 (PA) 的先前所有者不是同一用户,则在更改帐户所有者时 Salesforce 触发联系人 (PA) 所有者更改失败
- mysql - 带有 REPLACE() 的 IN() 不能按预期工作