I am developing an application which require accessing a website for data, and will show that data on device. I wants to fetch data from Internet in background and show ProgressDialog or ProgressBar on device and when application receive response from server app will dismiss the dialog or bar an开发者_JAVA百科d will show data .
For this i am using AsyncTask -
code for AsyncTask is as follows--
ServerTask extends AsyncTask {
@Override
protected void onPreExecute() {
dialogAccessingServer = new ProgressDialog(ctx);
dialogAccessingServer.setMessage(shownOnProgressDialog);
dialogAccessingSpurstone.show();
}
@Override
protected ServerResponse doInBackground(String... urlArray) {
String urlString = urlArray[0];
HttpResponse serverResponseObject = null;
//finding HttpResponse
return serverResponseObject;
}//end of doInBackground
@Override
protected void onPostExecute(HttpResponse serverResponseObject){
dialogAccessingSpurstone.dismiss();
}
}
and calling this code as follows--
ServerTask serverTaskObject = new ServerTask();
serverTaskObject.execute();
HttpResponse response = serverTaskObject.get();
//performing operation on response
but ProgressDialog is not shown.(I guess the reason for it is the thread is not complete and android invalidate only when thread has completed).
My Questions -- 1- If my guess is right ? If yes then how I should implement it? 2- If there is any other better way to do this?
thanks
Following is a template code that displays a ProgressDialog while a task is executing in background:
class GetTask extends AsyncTask<Object, Void, String>
{
Context mContext;
ProgressDialog mDialog = null;
GetPhotoFeedTask(Context context)
{
mContext = context;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
mDialog = new ProgressDialog(mContext);
mDialog.setMessage("Please wait...");
mDialog.show();
}
@Override
protected String doInBackground(Object... params)
{
// do stuff in background : fetch response
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setProgressBarIndeterminateVisibility(false);
// mDialog.dismiss();
}
}
and you invoke it from your activity using new GetTask(this).execute()
statement;
Note: Note that while displaying a ProgressDialog
if the user switches the Orientation or causes event that ensues one, the code might break. It is advised to use Managed Dialogs for such cases.
If there is some pending work on UI thread 'Progress dialog' will not appear, so dialog.show() should be the last line on UI thread and any further work should be done in onPostExecute() method.
精彩评论