在我的 Android
应用程序中,当用户点击 Sales
按钮时,它会显示另一个 View 来执行销售。
如果所选客户的 GST 许可证到期日期少于 7 天并且即将到期,我会在实现警报对话框以向用户显示警告消息之前,我的应用程序正常运行,没有任何问题。现在,如果我没有为这两个变量声明 final
,customer
和 v
,我将收到以下错误消息。
Cannot refer to a non-final variable
customer
inside an inner class defined in a different methodCannot refer to a non-final variable
v
inside an inner class defined in a different method
我明白了
The reference declared as final cannot be modified once it is initialized.
那么,如果我将这两个变量分配为 final
会发生什么?它总是包含相同的值?有人可以向我解释为什么编译器给我这些错误以及为什么我应该为这两个变量声明 final
吗?
这是我的源代码:
private OnClickListener salesBtnClick = new OnClickListener() {
@Override
public void onClick(View v) {
Customer customer = salesCustAdpt.getSelectedCustomer();
if (customer != null) {
Date expiryDate = customer.getGSTLicenseExpiryDate();
if (checkCustomerGSTLicenseExpiryDate(expiryDate)) {
AlertDialog.Builder builder = new AlertDialog.Builder(SalesCustomerActivity.this);
builder.setCancelable(false)
.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
//Perform sales here!
Intent intent = null;
intent = new Intent(v.getContext(), SalesActivity.class);//Error msg here!
Bundle bundle = new Bundle();
bundle.putSerializable("selCustomer", customer);//Error msg here!
intent.putExtra("bundle", bundle);
startActivity(intent);
finish();
} catch (Exception ex) {
AddPlusUtil.displayErrorMsg(
SalesCustomerActivity.this,
ex);
}
}
});
AlertDialog alert = builder.create();
alert.setTitle("Warning Message");
String errMsg = "GST License Expiry Date of selected customer is \n" + expiryDate + " and going to expire soon.";
alert.setMessage(errMsg);
alert.setIcon(android.R.drawable.stat_notify_error);
alert.show();
} else {
//Perform Sales
}
}
}
}
最佳答案
定义Customer时,使用final:
final Customer customer = salesCustAdpt.getSelectedCustomer();
此外,在您的 onClick 方法中,将 View 设置为最终 View :
public void onClick(final View v) {
希望这有帮助:)
关于java - Android:Java 不能引用非最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19150288/