Error "is not an enclosing class"

1

I'm doing a Handler exercise just to test how it works, but I'm trying some problem I can not figure out.

This is my main 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 for 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 someone please give me a hand? Thank you in advance!

    
asked by anonymous 01.12.2016 / 14:19

2 answers

3

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

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

Using MainActivity.this is referring to the object MainActivity as if it were the current object but the current object is of type TestHandler .

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

To have MainActivity.this valid within the TestHandler class, MainActivity must "wrap" the TestHandler class, in> TestHandler must be an inner MainActivity class.

Another alternative is to pass the MainActivity to the constructor of the TestHandler class to use it in Toast .     

01.12.2016 / 15:31
1

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

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

Enter in TesteHandler

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

In your Toast, change to:

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

I hope I have helped.

    
01.12.2016 / 14:44