Reputation: 2120
I have an AsyncTask which can publish progress to a main activity.
I also have a DialogFragment with ProgressBar which I create in my main activity.
In the main activity, I first execute the AsyncTask, then create the DialogFragment.
processTask = new ProcessImageAsyncTask(dataPathFile, lang, this, tessBaseApi);
processTask.execute(bitmap);
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
DialogFragment dialog = new TessProgressDialog();
dialog.setCancelable(true);
dialog.show(fragmentManager, "tessProgress");
I would like to update the progress bar when the main activity receives an update from the async task. Any ideas?
Upvotes: 0
Views: 531
Reputation: 2120
Basically I found the solution myself while writing the question, but I couldn't find any other answers, so here it is:
Solution is to override onAttachFragment in the main activity:
@Override
public void onAttachFragment(Fragment fragment)
{
if (fragment instanceof TessProgressDialog)
{
try {
// Instantiate the NoticeDialogListener so we can send events to the host
progressListener = (TessProgressUpdaterInterface) fragment;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(fragment.toString()
+ " must implement NoticeDialogListener");
}
super.onAttachFragment(fragment);
}
}
And the TessProgressDialog would implement TessProgressUpdaterInterface
public class TessProgressDialog extends DialogFragment implements TessProgressUpdaterInterface
{
private ProgressBar mProgressBar;
@Override
public void onUpdate(int p)
{
if(mProgressBar != null)
mProgressBar.setProgress(p);
}
}
And finally, I have an interface TessProgressUpdaterInterface:
public interface TessProgressUpdaterInterface
{
void onUpdate(int p);
}
Now just call the below whenever you receive an update from the async task
if(progressListener != null)
progressListener.onUpdate(progressValues.getPercent());
Upvotes: 1