I have an onClickListener that triggers a network call so I would like to have some way to show the user that communications are in progress. The problem I am running into is that I can’t seem to throw up a ProgressDialog or change the UI in any way for that matter before the call is made inside the onClick Listener. All of the code works just fine, but the UI changes don’t come into effect until after all the code in onClickListener runs.
I was wondering if my problem is simply that an anonymous inner class like an onclicklistener can only update the UI at the end of its run? Or maybe my code is just bad.
Thanks in advance
Below is the code for the onclick Listener :
relayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cPanel.throwProgress(NCDTCPRelayActivity.this);
System.out.println(tvSocketConnection.getText().toString());
if (relayStatusArray[relayNumber] == 0)
{
if (cPanel.TurnOnRelay(relayNumber, 1) == false)
{
changeTitleToRed();
}else{
changeTitleToGreen();
}
}
else {
if (cPanel.TurnOffRelay(relayNumber, 1) == false){
changeTitleToRed();
}else{
changeTitleToGreen();
}
}
cPanel.hideProgress(NCDTCPRelayActivity.this);
}
});
Here is the code for the throwProgress and hideProgress respectively (these are in a subclass of the activity):
public boolean throwProgress(Context mContext) {
System.out.println("INSIDE THROWPROGRESS");
try {
tempDialog = ProgressDialog.show(mContext, "Connecting", "Connecting", true);
}
catch (RuntimeException e) {
return false;
}
return true;
}
public boolean hideProgress(Context mContext) {
System.out.println("OUTSIDE THROWPROGRESS");
tempDialog.hide();
return true;
}
**Edit
Here is the new code for the onClickListener that I put the runnable in:
public void onClick(View v) {
cPanel.throwProgress(NCDTCPRelayActivity.this);
System.out.println(tvSocketConnection.getText().toString());
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (relayStatusArray[relayNumber] == 0)
{
if (cPanel.TurnOnRelay(relayNumber, 1) == false)
{
changeTitleToRed();
}else{
changeTitleToGreen();
}
}
else {
if (cPanel.TurnOffRelay(relayNumber, 1) == false){
changeTitleToRed();
}else{
changeTitleToGreen();
}
}
cPanel.hideProgress(NCDTCPRelayActivity.this);
relayStatusArray = cPanel.getBankStatus(1);
updateButtonText();
}
});
}
Changing UI from your click handler should work just fine. The problem is likely that you’re doing some heavy work on the UI thread and it’s blocking it so that the dialog is not really updated until after all of that work is done. Try moving all the heavy lifting into an AsyncTask (read this doc if you’re unfamiliar with it) hiding the dialog when the task is complete and see if that fixes it.