Reference main class variable, in a @Override

Asked

Viewed 81 times

1

We can reference a variable of the main class, for example within the method onCreate of the two forms (with or without the this):

public class NovoRegistro extends AppCompatActivity {

TextView data, horario;
int dia, mes, ano;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_novo_registro);

       this.data = findViewById(R.id.tvwData);
       horario = findViewById(R.id.tvwHorario);
   }
}

But if I’m inside a superscript method of another class, I can’t use the this, would not be pulling from the main class of the method.

Example:

public void datePicker(View v) {
        DatePickerDialog dp = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker datePicker, int ano, int mes, int dia) {
                mes = mes + 1;
                String dataSelecionada = (dia + "/" + mes + "/" + ano);
                data.setText(dataSelecionada);
            }
        }, ano, mes, dia);
        dp.show();
    }

In the above example, the method onDateSet is returning to me ano, mes, dia just like in my main class.

What would be the best way to set the properties ano, mes, dia of my main class, with the properties of the method ?

1 answer

3


The problem here is that the method variables have the same name as the Activity fields.
Use NovoRegistro.this to access the Novoregistro object (your Activity):

NovoRegistro.this.ano = ano;
NovoRegistro.this.mes = mes;
NovoRegistro.this.dia = dia;

this is a reserved word which in this context is a reference to the current object. It is like a variable(field) that stores the current object. To reference it in a Inner class shall include the name of the Outer class: NomeDaOuterClasse.this.

Like NovoResgisto.this represents the instance of Novoregisto can, through it, access all its members.

  • Great Ramaral teacher ! I will have to leave the properties as static in that correct case ? Is there some other way or only that ?

  • 2

    Not, NovoRegistro.this represents the instance.

  • Very good !! Tested with this, and really do not need to leave the static properties. Thanks ! Hug !

  • 1

    Another way would be for Novoregistro to have a method for "setar" these attributes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.