How to use AsyncTask to show a ProgressDialog while doing background work in Android?
Place your ProgressDialog
in onPreExecute
, sample code below:
private ProgressDialog pdia;
@Override
protected void onPreExecute(){
super.onPreExecute();
pdia = new ProgressDialog(yourContext);
pdia.setMessage("Loading...");
pdia.show();
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pdia.dismiss();
}
and in your onClickListener
, just put this line inside:
new EfetuaLogin().execute(null, null , null);
Adding android progress dialog inside Background service with AsyncTask,Getting FATAL Exception
Actually you can't start a progress dialog from a service, because it needs the activity context not application context which come to be null in your case.
More info here:
link1 , link2 and link3
If you want to trigger progress dialog based on service action, you may use Observer design patter, look here.
Update:
If your app is running, you can use Handler and run it each 5 minutes.
Here is a complete example:
public class TestActivity extends AppCompatActivity {
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//
new Asynctask_Incident(TestActivity.this).execute("url");
handler.postDelayed(this, 5 * DateUtils.MINUTE_IN_MILLIS);
}
}, 0);
}
public class Asynctask_Incident extends AsyncTask<String, Void, Void> {
ProgressDialog pDialog;
Context appContext;
public Asynctask_Incident(Context ctx) {
appContext = ctx;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(appContext);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setCancelable(false);
pDialog.setMessage("Please Wait Updating Data From...");
pDialog.show();
}
@Override
protected Void doInBackground(String... params) {
try {
getAPICall();
} catch (Exception e) {
e.printStackTrace();
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
return null;
}
private void getAPICall() {
//5 seconds delay for test, you can put your code here
try {
Thread.sleep(5 * DateUtils.SECOND_IN_MILLIS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
}
Android Display Progress Dialog while doing a background task
You need to use an AsyncTask to execute your download and ProgressBar instance to show a circular progress.
There are many resources you can find which describe exactly how to use the combination to do what you want.
How to set progress dialog in AsyncTask
You should Override onPreExecute() method before doInBackground method.
ProgressDialog myPd_bar;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar=new ProgressDialog(AndroidGridLayoutActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(title);
myPd_bar.show();
super.onPreExecute();
}
Then you should Override onPostExecute() method after doInBackground method.
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
myPd_bar.dismiss();
}
You can find more information from this link
Android ASync task ProgressDialog isn't showing until background thread finishes
This works for me
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(viewContacts.this);
dialog.setMessage(getString(R.string.please_wait_while_loading));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
ProgressDialog in AsyncTask
Fixed by moving the view modifiers to onPostExecute so the fixed code is :
public class Soirees extends ListActivity {
private List<Message> messages;
private TextView tvSorties;
//private MyProgressDialog dialog;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.sorties);
tvSorties=(TextView)findViewById(R.id.TVTitle);
tvSorties.setText("Programme des soirées");
new ProgressTask(Soirees.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
@Vladimir, thx your code was very helpful.
Android Async Task progress on background
We use Async Task for operations less than 10 seconds because it works on main thread. If your operation is more than this, you should use intent service. It works on background thread.
Related Topics
Pop Up Window Over Android Native Incoming Call Screen Like True Caller Android App
Round Corner for Bottomsheetdialogfragment
How to Add a Dropdown Item on the Action Bar
Android Imagebutton with a Selected State
Android Sdk Asynctask Doinbackground Not Running (Subclass)
Creating Temporary Files in Android
Android: Binding Data from a Database to a Checkbox in a Listview
Eclipse Error "Adb Server Didn't Ack, Failed to Start Daemon"
How to Programmatically Turn Off Wifi on Android Device
Calling Startactivity() from Outside of an Activity
Locationsettingsrequest Dialog to Enable Gps - Onactivityresult() Skipped
How to Avoid Soft Keyboard Pushing Up My Layout
How to Interface with the Badgeprovider on Samsung Phones to Add a Count to the App Icon
How to Create Empty Constructor for Data Class in Kotlin Android
Android Textview Padding Between Lines
How to Handle Imeoptions' Done Button Click
How Permission Can Be Checked at Runtime Without Throwing Securityexception