Error "is not an enclosing class"

Asked

Viewed 2,323 times

2

I’m doing an exercise in Handler just to test how it works, but I’m trying some problem that I can’t understand.

This is my master class code:

public class MainActivity extends Activity {

protected static final int MENSAGEM_TESTE = 1;
private Handler handler = new TesteHandler();
Button button;

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

    button = (Button) findViewById(R.id.button);
    button.setText("Atualizar o texto em 3 segundos");
    button.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View view) {
          //Cria msg com delay de 3 seg
            Message msg = new Message();
            msg.what = MENSAGEM_TESTE;
            //Envia msg
            handler.sendMessageDelayed(msg, 3000);
        }
    });

}
}

And this is the code of my class TesteHandler:

import static com.exercicios.handler.MainActivity.MENSAGEM_TESTE;

public class TesteHandler extends Handler {
    @Override
    public  void handleMessage(Message msg) {
        switch (msg.what) {
           case MENSAGEM_TESTE:
                     Toast.makeText(MainActivity.this, "A mensagem chegou!", Toast.LENGTH_SHORT).show();
                 break;
        }
    }
}

Android Studio is returning me the following error:

'com.exercicios.Handler.Mainactivity' is not an enclosing class.

I’m not finding what I need to fix, can anyone give me a help, please? Thanks already!

2 answers

5


In this situation the error "not an enclosing class" is due to incorrect use of this.

this, within an instance or constructor method, refers to the current object.

When using MainActivity.this is referring to the object MainActivity as if it were the current object but the current object is like Testehandler.

Translating "not an enclosing class" would be "is not an engaging class".

Why MainActivity.this is valid within the class Testehandler, Mainactivity has to "involve" the class Testehandler, that is to say, Testehandler must be a inner class of Mainactivity.

Another alternative is to pass the Mainactivity to the class builder Testehandler so you can use it on Toast.

1

I believe this message is occurring when performing the Toast.makeText(MainActivity.this in class TesteHandler.

Try passing the context on Handler handler = new TesteHandler(getApplicationContext());

Insert into the TesteHandler

private Context ctx;
public TesteHandler(Context ctx){
    this.ctx = ctx;
}

In your Toast, modify to:

Toast.makeText(ctx,, "A mensagem chegou!", Toast.LENGTH_SHORT).show();

I hope I could have helped.

Browser other questions tagged

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