Android: Java cannot refer to a non-final variable
在我的
如果所选客户的GST许可证到期日期少于7天并且即将到期,则在实施警报对话框之前,我的应用程序工作正常,没有任何问题,向用户显示警告消息。现在,如果我不向这两个变量(
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.
那么,如果我把这两个变量指定为
这是我的源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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 " + expiryDate +" and going to expire soon."; alert.setMessage(errMsg); alert.setIcon(android.R.drawable.stat_notify_error); alert.show(); } else { //Perform Sales } } } } |
定义客户时,使用final:
1 | final Customer customer = salesCustAdpt.getSelectedCustomer(); |
另外,在onclick方法中,将视图设置为final:
1 |
希望这有帮助:)
在您的类中定义
创建一个全局视图对象,并将其分配给您的
1 | globalView = v; |
用这个全局视图来表示呼叫意图。
另外,您可以使用