Ashwin
Ashwin

Reputation: 13537

final variable in android programming

This is the code I am using in android programming

EditText pass1,pass2;
Button register=(Button) findViewById(R.id.register);
register.setOnCllickListener(new OnClickListener(){
public void onClick(View v)
{
 passq=(EditText) findViewById(R.id.password_fill);
}
});

But i always get an error:

Cannot refer to non-final variable inside an inner class defined in different method.

Even after I declare the pass1 as final, I get the following error:

The final local variable pass1 cannot be assigned since it is defined in an enclosing type.

But why is this error coming and how can I remove it? I have been encountering it many times.

Upvotes: 0

Views: 4024

Answers (3)

Sniper
Sniper

Reputation: 2452

You have to declare edit text globally. The reason for this is in your activity class you have a method called "onCreate" where you declared the Edit text "pass1" and you trying to define by another pre defined method "setOnClickListener". This is not possible. So you have to declare it globally or as final.

Upvotes: 2

Padma Kumar
Padma Kumar

Reputation: 20041

//declare your editext in global

or

final EditText pass1;
Button register=(Button) findViewById(R.id.register);
register.setOnCllickListener(new OnClickListener(){
public void onClick(View v)
{
 pass1=(EditText) findViewById(R.id.password_fill);
or
EditText pass2=(EditText) findViewById(R.id.password_fill);
}
});

Upvotes: 1

Newts
Newts

Reputation: 1372

When we use any variable in anynomus class then we have to use final variable.

So use

final EditText passq;

then use it in onClick method.

Upvotes: 1

Related Questions