tags:

views:

89

answers:

2

Hi everyone,

I'm trying to do a simple global exception handler in my Android app and I am having troubles:

public class TicTacToe extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            Toast.makeText(this, "TOAST", Toast.LENGTH_LONG);

        }
    });

    setContentView(R.layout.main);
    }
}

I'm a rather new with both Android AND java but in .NET that would work. Can't I access local variable from anonymous methods in java? If so, how should I rewrite it?

Thanks, Vitaly

+4  A: 

You can but not in that way. this is referred to the UncaughtExceptionHandler object.

Change this to TicTacToe.this

Also you should have a compile time error. It isn't?

Francesco
Hi. You are correct. I did have a compile error, sorry for not posting it. Anyway, it seems that it helped. Thanks.
VitalyB
To elaborate a little, when you do this, you are actually forming a new class. It has a .class file (or the Dalvik equivalent I guess) and everything. So "this" is the instance of that class. Google "anonymous inner class" for more information.
MatrixFrog
A: 

As mentioned in another answer, the trick is this is shadowed. Another way to get around that is to add a method in the outer class that returns this.

It realize this junks up the class signature a little bit, but if you keep the method private, that doesn't seem like a big deal. Does anybody have comments on how this is better or worse than other solutions?

public MyOuterClass {

  private MyOuterClass getThis() {
    return this;
  }

  private void outerClassMethod(new MyAnonymousClass() {
    public void anonymousClassMethod() {
        doSomething(getThis());
    }
  });
}
allclaws
why would anyone use this obscure way, when there is a proper way?
unbeli