HelloCW
HelloCW

Reputation: 2255

Why will it cause the error "Cannot refer to a non-final variable"?

The following code get the error "Cannot refer to a non-final variable myid inside an inner class defined in a different method", why? Thanks!

private void DeleteSingleSMS(long myid){
    AlertDialog.Builder builder = new Builder(this);
    builder.setMessage(getString(R.string.DeleteContent));
    builder.setTitle(getString(R.string.DeleteTitle));

    builder.setPositiveButton(getString(R.string.DeleteOK), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            String uri = "content://sms/" +myid;            
            getContentResolver().delete(Uri.parse(uri), null, null);    
        }
    });

    builder.setNegativeButton(getString(R.string.DeleteCancel),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });

    builder.create().show();        
}

Upvotes: 0

Views: 60

Answers (1)

Blackbelt
Blackbelt

Reputation: 157457

because myid is not declared as final. Change

DeleteSingleSMS(long myid)

to

DeleteSingleSMS(final long myid)

Upvotes: 2

Related Questions