I am having a strange behavior with threads and a `onclick listener instance in some phones (strange that its not by android version, have test it in a GalaxyII with android 4.03 and work, in a Samsumg Galaxy Tab with 3.2 works fine and in a HTC EVO Design 4G with android 4.03 and a HTC EVO 4G with android 2.3.3 doesn’t work) so here is the issue:
I have a async class that calls a web service and blocks the screen until the service finishes, then the thread notifies the UI that the service call is finished so the UI shows a modal screen making a addView(GenerateView) to the activity. That works fine until I need to avoid the multiple clicks in the button that triggers the action because multiple views are adding to the activity. So I implement a custom OnClickListener like this:
public abstract class OnOneClickListener implements OnClickListener {
private boolean clickable;
public OnOneClickListener(){
clickable = true;
}
public final void onClick(View v) {
if (clickable) {
clickable = false;
onOneClick(v);
}
}
public abstract void onOneClick(View v);
public void reset() {
clickable = true;
}
}
So I implement the custom onclick, block the clickabilty of the button, call the web service and when it finishes in the function that creates and returns the view to add to the activity as a modal windows calls reset() and allows the click in button again. That function receives the instance of the class by parameters. That works like a charm in the phone that mentioned before but in the HTCs when i debug can see that the OnOneClickListener() function modify the clickable variable and the reset() function doesn’t see it!! and it happens in the other way too, like if the call of the functions where in two different instances of the class and it NOT!! and thats just one issue that im having with HTCs and threads, the most incredible one.
So here goes my questions:
- Is some knowed issues with HTCs and threads??
- Is there some work around?? (Im using AsyncTask to make the calls and it works perfect until now)
In fact anything that you can tell me that help me understand where is the fail will be very helpful because it’s driving me crazy.
You’re lucky it works on some phones, because it does not have to. If you change
clickablefield on one thread, you should explicitly synchronize for the other thread to see the changes.Try making
clickablefieldvolatile. Jeremy Manson has a great article aboutvolatileand other good Java concurrency articles.I also suggest you to implement what you want the other way – just make the button disabled on first click until your web service gives you a result. Disabled button is a clear message to user that you handled the click and are doing something while it is disabled.
Check also Happened-before term on Wikipedia.