Here is my code:
final Foo myFoo = new Foo(new Inner() {
@Override
callback(){
myFoo.bar();
}
});
(With actual function names)
final MyArrayAdapter aa = new MyArrayAdapter(new View.OnClickListener() {
@Override
onClick(){
aa.notifyDataSetChanged();
}
});
Java is giving me an error about how myFoo might not have been initialized. Is there any way to fix this? I can potentially set the callback to null when I construct the object and then change it afterwards, but I'd hope for there to be a cleaner way. Any ideas? (Also that wouldn't work if Foo wasn't written by me and didn't expose an interface to change the callback later)
In case anyone is curious, in my specific scenario, Foo is an ArrayAdapter, and the bar is notifyDataSetChanged(). What is displayed by the adapter depends on the values of the items in the array, and those values change when they are clicked on. The callback is the clickListener.
Short answer is that you definitely can't do that in Java, but the compiler already told you that. You're trying to create two objects at once with references to each other, it's a chicken and egg problem. Bottom line, you have to create ONE of them first.
A suggestion is a two step creation:
....
final MyArrayAdapter aa = new MyArrayAdapter();
aa.initializeButtonClickListener();
....
and then add the 'initialize' method to the adapter.
public void initializeButtonClickListener(){
this.button.setOnClickListener(new View.OnClickListener() {
@Override
onClick(){
notifyDataSetChanged();
}
});
}
Because that construction is somewhat complicated (ie, more complicated than simply calling a constructor), I'd recommend then pulling those two lines in to a MyArrayAdapter
factory method, and making the constructor private.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With