Why should I use onPrepareDialog etc. to show a ProgressDialog in Android? - java

I'm currently using the following code to show / hide a ProgressDialog in my Andorid app (called from withing MyActivity):
private void startTask() {
new MyTask().execute();
}
private class MyTask extends AsyncTask<A, String, C> {
private ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
this.pd = ProgressDialog.show(MyActivity.this, "Title", "Message", true, true);
pd.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
MyTask.this.cancel(true);
}
});
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
this.pd.setMessage(values[0]);
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(MyActivity.this, "cancelled", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(RequestResult result) {
super.onPostExecute(result);
this.pd.dismiss();
}
}
Now, since I read so much about onCreateDialog in Activities, I just want to know if my way of doing it has any downsides I didn't think of, or even why I should prefer the onCreateDialog mechanism.

[UPDATED]
The problem with this approach is that in case Activity will be destroyed (e.g. on rotation) your AsyncTask will retain it in memory, thus create a temporary memory leak. Also, it will cause an IllegalArgumentException while attempting to access ProgressDialog after activity's onDestroy().

Related

How to show ProgressDialog when AsyncTask start gathering data from the server till when it gets all the data

I would like to make an app which displays some data from the server. When I log in as an admin, I would like there to be a progress dialog until the application gets all the data from the server.
I have 3 Classes. Main Activity(login screen), SecondActivity(displays data) and BackgroundWorker(which extends AsyncTask).
I know that in on postExecute I have to close ProgressBar
Override
protected void onPreExecute() {
if(activity.getClass() == MainActivity.class) {
this.progressDialog.setMessage("Please wait for a while.");
this.progressDialog.setTitle("Login");
this.progressDialog.show();
}
else
super.onPreExecute();
}
#Override
protected void onPostExecute(final String result) {
if(activity.getClass() == MainActivity.class) {
new CountDownTimer(1000, 500) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
System.out.println(result);
if (result.equals("Username or password is not correct")) {
alertDialog.setMessage(result);
alertDialog.show();
} else if(result.equals("is Admin")) {
Intent intent = new Intent(activity,Admin.class);
intent.putExtra("username",user);
activity.startActivity(intent);
activity.finish();
}
progressDialog.dismiss();
}
}.start();
}
I have made like this for login Screen but I don't think it is wise to delay the application on purpose. And also my implementation doesn't work if I call AsyncTask class twice in one activity. Any suggestion?
You can use this code:
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// Do your request
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pd != null)
{
pd.dismiss();
}
}
}
Take a look at this link, if you want!
Good luck with your android development!

onProgressUpdate is not being called android

I have this GetAllUsers(); in onCreate and I have this
private void GetAllUsers() {
(new LoadingUsers(this)).execute();
}
Then I have this
private class LoadingUsers extends AsyncTask < Void, Integer, String > {
String TAG = getClass().getSimpleName();
AlertDialog.Builder builderSingle;
ArrayAdapter < String > arrayAdapter;#
SuppressWarnings("unused")
Context mContext;
public LoadingUsers(Context context) {
super();
mContext = context;
}
protected void onPreExecute() {
// prgDialog.show();
// builderSingle = new
Log.d(TAG + " PreExceute", "On pre Exceute......");
}
protected String doInBackground(Void...arg0) {
Log.d(TAG + " DoINBackGround", "On doInBackground...");
return null;
}
protected void onProgressUpdate(Integer...a) {
super.onProgressUpdate(a);
Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
// prgDialog.hide();
Log.d(TAG + " onPostExecute", "" + result);
MainActivity.this.pd.dismiss();
}
}
I wanted to put a builderSingle = new AlertDialog.Builder(MainActivity.this); inside the protected void onProgressUpdate(Integer... a) { which has a AsyncHttpClient client = new AsyncHttpClient(); but unfortunately the onProgressUpdate does not get called at all. I know this because the log does not show. All other log are showing except the onProgressUpdate I have also have
#
Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "On Destroy .....");
}
#
Override
protected void onPause() {
super.onPause();
Log.i(TAG, "On Pause .....");
}
#
Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "On Restart .....");
}
#
Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume .....");
}
#
Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
}
#
Override
protected void onStop() {
super.onStop();
Log.i(TAG, "On Stop .....");
}
OnStart and OnResume are being log as well.
Why is onProgressUpdate not being called?
How to call the onProgressUpdated correctly?
Update
onPostExecute is being called as well on the onProgressUpdate is not
onProgressUpdate is called on the main thread each time publishProgress is called from within doInBackground (on the background thread). This facility is provided for your convenience if you choose to use it. It's primarily useful if your task involves some kind of loop, in which case you can call publishProgress at each iteration. If your task simply invokes some other code, and all the processing happens somewhere you can't control, then the publishProgress/onProgressUpdate mechanism isn't going to be useful to you. In that case, you might decide to display an indeterminate progress bar before starting the task and then hide the indeterminate progress bar after it's completed.
It should be very simple
private class LoadingUsers extends AsyncTask< Void, Integer, String > {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(getContext(), null, "Loading users...", false);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}
#Override
protected String doInBackground(Void... params) {
// Doing something in loop
int max = 1024;
for (int i = 0; i < max; i++) {
int percentageCompleted = i*100/max;
publishProgress(percentageCompleted);
}
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
dialog.dismiss();
}
}
Let me know if you didn't understand what is this code.
Your code may need following function:
#Override
protected void onProgressUpdate(Integer a) {
super.onProgressUpdate(a);
}
Override the function instead of just copy past,
use keyword #Override

ProgressDialog new Activity Asynctask is not showing, why?

I made a AsyncTask class with the following code
public class removeDialog extends AsyncTask<Void, Void, Void> {
Context c;
ProgressDialog asyncDialog;
String page;
public removeDialog(Context c, String page) {
this.c = c;
this.page = page;
asyncDialog = new ProgressDialog(c);
}
#Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();
if (page == "algemeneVoorwaarden") {
Intent intent = new Intent(c, algemeneVoorwaarden.class);
c.startActivity(intent);
}
if (page == "contact") {
Intent intent = new Intent(c, contactTest.class);
c.startActivity(intent);
}
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
//don't touch dialog here it'll break the application
//do some lengthy stuff like calling login webservice
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}
First time I tried:
on the first time I see an ProgressDialog, but the second time I want to open the activity I get nothing.
Second time I tried:
I get no ProgressDialog even the first time I try.
I execute my code in an AsyncTask class, code:
voorwaarden.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new removeDialog(c, "algemeneVoorwaarden").execute();
}
});
Does someone know why it isn't working? Please help me.
Your dialog will be dismissed as soon as it's shown, because your doInBackground is empty. Try adding a Thread.sleep() with a few seconds, just to simulate a delay.
Also, I suspect that the new activities you're starting will leave your dialog behind. So I would suggest you to test the code without these new activities for now.
public class RemoveDialog extends AsyncTask<Void, Void, Void> {
ProgressDialog asyncDialog;
public RemoveDialog(Context c) {
asyncDialog = new ProgressDialog(c);
}
#Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(3000);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}

Android external Async Task with callback, do i need to dispose the callback?

Got a small issue and would like some advice on it.
This is my Async task
public class DummyTask extends AsyncTask<Void, Void, Void> {
private OnDummyTaskComplete mOnDummyTaskComplete;
public DummyTask(OnDummyTaskComplete listener) {
mOnDummyTaskComplete = listener;
}
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
mOnDummyTaskComplete.onDummyTaskComplete();
}
}
This is my callback
public interface OnDummyTaskComplete {
void onDummyTaskComplete();
}
This is the activity that implements the callback starts the async task.
public class MainActivity extends ActionBarActivity implements OnDummyTaskComplete {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DummyTask dummyTask = new DummyTask(this);
dummyTask.execute();
}
Do I need to dispose of the callback to avoid a memory leak?
Is the following code required?
#Override
protected void onPostExecute(Void aVoid) {
mOnDummyTaskComplete.onDummyTaskComplete();
mOnDummyTaskComplete = null;
}
Do I need to dispose of the callback to avoid a memory leak?
No. Shortly after onPostExecute() is run, the AsyncTask instance will lose scope, along with its reference to mOnDummyTaskComplete. Just be sure not to reference mOnDummyTaskComplete (or anything else that may contain a reference to MainActivity) from within doInBackground; otherwise, you do open yourself up to a Context leak. See this related SO issue for details.

Android SDK - running functions in the background

I have a function which can vary in the time it takes to finish. I would like to display a progress dialog whilst this function is operating.
I am aware that you can use a 'Thread' to achieve this. Can someone point me in the right direction for doing this ?
EDIT:
Here is the code I am using:
private class LongOperation extends AsyncTask<String, Void, String>
{
ProgressDialog dialog;
public Context context;
#Override
protected String doInBackground(String... params) {
if (!dialog.isShowing())
dialog.show(); // Just in case
return null;
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute()
{
dialog = ProgressDialog.show(context, "Working", "Getting amenity information", true);
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
#Override
protected void onProgressUpdate(Void... values) {
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
}
this is the Asnyc class. The user selects an option from the menu, and this is then executed:
longOperation.execute(""); // Start Async Task
GetAmenities(Trails.UserLocation); // Long function operation
You should use AsyncTask for this purpose. See Android developers website and How to use AsyncTask.
Some sample code:
private class LongRunningTask extends AsyncTask<Void, Boolean, Boolean> {
private ProgressDialog progress;
protected void onPreExecute() {
progress = ProgressDialog.show(yourContext, "Title", "Text");
}
#Override
protected Boolean doInBackground(Void... params) {
return true;
}
protected void onPostExecute(Boolean result) {
if(result) {
progress.dismiss();
}
}
}
Take a look at this page:
Progress Bar Reference
Greetings
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b = loadImageFromNetwork();
}
}).start();
}
taken from here
http://developer.android.com/resources/articles/painless-threading.html

Categories