In my app i m trying to fetch data from server and storing in database.
When it is doing all these work i want at that time progressdialog should show, if successfully data fetches then dialog should close and some alertDialog should show for msg "successfully data fetched". and if any n/w problem there, then it should show different msg that "problem with n/w".
for that i am doing like below,
public void onClick(View arg0) {
myProgressDialog = ProgressDialog.show(
getParent(), "Please wait...",
"Doing upgrade...", true);
new Thread() {
public void run() {
try {
upgradeAll();//function where data fetched from server
sleep(5000);
} catch (Exception e) {
}
// Dismiss the Dialog
myProgressDialog.dismiss();
Toast.makeText(UpgradeAllTableData.this, "Due to some internal problem \n" +
"it couldnot update..", Toast.LENGTH_LONG).show();
}
}.start();
}
AsyncTask code,
private class UpgradeTask extends AsyncTask<Context, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(UpgradeAllTableData.this);
#Override
protected void onPreExecute() {
System.out.println("In onPreExecute ");
Dialog.setTitle("Loading");
Dialog.setMessage("Please wait for few seconds...");
Dialog.show();
}
#Override
protected Void doInBackground(Context... params) {
System.out.println("In doInBackground ");
upgradeAll();
System.out.println("In doInBackground after fetching");
return null;
}
#Override
protected void onPostExecute(Void unused) {
System.out.println("In onPostExecute ");
Dialog.dismiss();
Toast.makeText(UpgradeAllTableData.this, "Problem with internet" , Toast.LENGTH_SHORT).show();
alertboxNeutral("Warning", "Problem with Internet Connection", "Okay","Try again");
}
}
Problem is Toast is not showing. why?
My question is which condition and where to give so that if any problem with n/w then it show some msg and success then show another msg.
Where i should write code for that?
Give me some suggestion.
Thank you
Not exactly an answer to your particular question, but have you considered AsyncTask? It's pretty much designed to handle situations like yours, where a task is performed async while showing some progress (and eventual result) on the UI thread. Alternativelly, you could broadcast an intent and have your activity catch it to show the toast, since your Toast should be show from your UI thread as well.
update:
AsyncTask reference - http://developer.android.com/reference/android/os/AsyncTask.html
What you are doing is totally wrong. UI thread handles all UI changes, but here you are creating ProgressDialog in UI thread and dismissing it in some Other Thread.. A solution is make use of AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
Related
I am trying to cancel a log run AsyncTask if a certain period of time exceeds (if AsyncTask is not automatically finised)
Below is the code where I setup my task to start with timeout
final ProfileDesc pdsc = new ProfileDesc();
pdsc.execute();
Thread th_pdsc = new Thread(){
public void run()
{
try{
pdsc.get(120000, TimeUnit.MILLISECONDS);
}
catch(Exception e){
pdsc.cancel(true);
((Activity)context).runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Download Time out. Please Try again later.", Toast.LENGTH_LONG).show();
}
});
}
}
};
th_pdsc.start();
below is the code for my AsynTask
private class ProfileDesc extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Header Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
protected void onPostExecute(Void params) {
super.onPostExecute(params);
dialogue.dismiss();
}
protected Void doInBackground(Void... arg0) {
//long run work
return null;
}
}
After two minutes it's still running. How can I set up the time out? Note: I have followed this link of Stack Overflow for this code.
What you had
ProfileDesc pdsc = new ProfileDesc();
pdsc.execute();
was enough. There is no need for a Thread. doInBackground is invoked on the background thread. So you can do you Network operations in doInbackgorund.
Secondly calling get makes AsyncTask no more Asynchronous as it blocks the ui thread
get(long timeout, TimeUnit unit) Waits if necessary for at most the
given time for the computation to complete, and then retrieves its
result
I guess you have misunderstood the use of Asynctask. Read the docs
http://developer.android.com/reference/android/os/AsyncTask.html
You may want to check this
Stop AsyncTask doInBackground method
Here new thread is not needed.Just remove "dialogue.setIndeterminate(true)". It means the "loading amount" is not measured.I think it's creating the problem.
I'm new to Android development. I've be working on Swing and SWT for several years. Both Swing and SWT has a stratage to execute code in UI thread sync and async. The typical usage is doing some time-consume staff in one thread then display the result in UI thread async.
So my question is, is there similiar stratage in Android? Here is my code. Parameter runnable is some time-consume code. This method will display a waiting dialog during the execution then EXPECT to show a Toast after it is finished. But the Toast need to be show in UI thread. So how to do that?
public static void showWaitingDialog(final Activity parent, final Runnable runnable, String msg) {
if (StringUtils.isEmpty(msg)) {
msg = "processing...";
}
final ProgressDialog waitingDialog = ProgressDialog.show(parent, "Please Wait...", msg, true);
// execute in a new thread instead of UI thread
ThreadPoolUtil.execute(new Runnable() {
public void run() {
try {
// some time-consume operation
runnable.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
waitingDialog.dismiss();
}
// TODO: How to display a Toast message here? execute some code in UI Thread.
}
});
}
And is there some words about Android UI system? Such as is it Thread-Safe, how thread works together and so on. Many Thanks!
There are several ways for doing that,
AsyncTask -
AsyncTask enables proper and easy use of the UI thread. This class
allows to perform background operations and publish results on the UI
thread without having to manipulate threads and/or handlers. Example for using AsyncTask
Service -
A Service is an application component representing either an
application's desire to perform a longer-running operation while not
interacting with the user or to supply functionality for other
applications to use. Example for Using Service.
IntentService -
IntentService is a base class for Services that handle asynchronous
requests (expressed as Intents) on demand. Clients send requests
through startService(Intent) calls; the service is started as needed,
handles each Intent in turn using a worker thread, and stops itself
when it runs out of work. Example for using IntentService.
You can use AsyncTask like this.
To call AsyncTask
new getAsynctask().execute("");
and here is the class for geting result.
class getAsynctask extends AsyncTask<String, Long, Integer> {
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Pass.this, null, "Please wait...");
}
protected Integer doInBackground(String... params) {
try {
// do your coding
return null;
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
try {
if (loading != null && loading.isShowing())
loading.dismiss();
} catch (Throwable t) {
Log.v("this is praki", "loading.dismiss() problem", t);
}
}
}
Whenever you are working with Separate thread which is not your UI thread the best way is to use Handler. Whenever you want to intimate user from your Thread, suppose a progress then send a message to Handler to so. Inside Handler you can handle message and write a code snippet to Change anything on UI. This is the preferred way for Android. see these link1 , link2 & link3
You use this AsynTask as a inner class of your activity. In do in background do the time consuming task you want to do and then in on postexecute you can show the text message.
call this from your main activity
initTask = new InitTask();
initTask.execute(this);
protected class InitTask extends AsyncTask<Context, Integer, String> {
#Override
protected String doInBackground(Context... params) {
// Do the time comsuming task here
return "COMPLETE!";
}
// -- gets called just before thread begins
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// -- called from the publish progress
// -- notice that the datatype of the second param gets passed to this
// method
#Override
protected void onProgressUpdate(Integer... values) {
}
// -- called if the cancel button is pressed
#Override
protected void onCancelled() {
super.onCancelled();
}
// -- called as soon as doInBackground method completes
// -- notice that the third param gets passed to this method
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Show the toast message here
}
}
Use a handler:
static final int SHOW_TOAST = 0;
public static void showWaitingDialog(final Activity parent, final Runnable runnable, String msg) {
if (StringUtils.isEmpty(msg)) {
msg = "processing...";
}
final ProgressDialog waitingDialog = ProgressDialog.show(parent, "Please Wait...", msg, true);
// execute in a new thread instead of UI thread
ThreadPoolUtil.execute(new Runnable() {
public void run() {
try {
// some time-consume operation
runnable.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
waitingDialog.dismiss();
}
handler.sendMessage(handler.obtainMessage(SHOW_TOAST));
}
});
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_TOAST:
//Toast here
break;
}
}
};
The Painless threading article from the android developer resources provides different alternatives depending on the specific SDK version.
Tips or ideas on how ProgressDialog can communicate with asyncTask.
For example when I click the button, the program will validate the input to internet, This is should not be interupted. so I use ProgressDialog.
After progressDialog.dismiss(), I need to refresh the view by calling the asyncTask.
I have tried some ways but it's failed, for example
* I execute asynTask after progressdialog.dismiss().
* put execution asynctask inside dialogbox after progressdialog thread.
in other word, is there any way to tell asynctask that progressdialog has been dismissed. Or is there communication such as message between threads ?
here is the example of my code:
btnPost.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stockProgressDialog = ProgressDialog.show(PostActivity.this,
"Please wait...", "Check the post");
new Thread() {
public void run() {
try{
/* Connect to Internet API */
stockProgressDialog.dismiss();
} catch (Exception e) { }
// Dismiss the Dialog
}
}.start();
new LookUpTask().execute();
}
});
Yes, there is a way to tell asyncTask that progressDialog has been dismissed. you can use one onDismissListener
#Override
public Dialog onCreateDialog(int id){
if(id==DIALOG_PROGRESS_DIALOG){
stockProgressDialog = new ProgressDialog(Main.this);
stockProgressDialog.setTitle("Please wait...");
stockProgressDialog.setMessage("Check the post");
stockProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
textView.setText("Waiting the 5 secs...");
myAsyncTask.execute("start it");
//Or myAsyncTask.cancel(true); if you want to interrupt your asyncTask
}
});
return stockProgressDialog;
} else return super.onCreateDialog(id);
}
You can cancel an AsyncTask by calling AsyncTask.cancel(..) and then start up a new AsyncTask. You are not supposed to run the AsyncTask as a parallel activity - it is supposed to be able to run and finish without outside intervention.
Extend async and look into returning a result from doInBackground. onProgress update can dismiss your Progress dialog under control of the async task. Handle the result from doInBackground in onPostExecute.
//create the task
theBackground = new Background();
theBackground.execute("");
--------
private class Background extends AsyncTask<String, String, String>{
protected String doInBackground(String...str ) {
publishProgress("##0");
//do a bunch of stuff
publishProgress(#001);
return("true");
}
protected void onProgressUpdate(String... str ) {
//do stuff based on the progress string and eventually
myProgressDialog.dismiss();
}
protected void onPostExecute(String result) {
}
}
I'm not sure why you're using a thread in one case, but an AsyncTask in another when you could just use two AsyncTasks... Actually, unless I'm missing something, in your case the most straightforward way is to combine the two bits of work into one AsyncTask and simply create and destroy the dialog in the AsyncTask callbacks. In pseudo-code:
onPreExecute
show dialog
doInBackground
do internet stuff
onPostExecute
update views
close dialog
Is there a reason why you're trying to update the views in its own AsyncTask? If you're updating views, you probably need to do the work in the UI thread anyway...
I'm trying to display a ProgressDialog to indicate that the user should wait while something uploads in the background, however, the device (galaxy tab) just freezes for the time that the upload happens and then when it comes out of its stupor it just goes to the next thing (having never displayed the ProgressDialog.
When I eliminate the upload, the dialog appears as expected. I'm guessing this is an async issue? The dialog simple never gets a time slice and by the time it does it's already been dismissed?
pd = ProgressDialog.show(getApplicationContext(),"", "Sending Image ...", true);
uploadImage(); //if I comment out this line, the dialog shows, otherwise not.
pd.dismiss();
Is there some way to block on the ProgressDialog line until it actually renders? Or am I overlooking something stupid (and obvious)?
This is similar to what you are doing.
Long story short use a AsyncTask and call uploadImage() inside doInBackground()
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(getApplicationContext(),"", "Sending Image ...", true);
Log.d(TAG, "onPreExecute()");
}
#Override
protected Void doInBackground(Void... params)
{
Log.d(TAG, "doInBackground() -- Here is the upload");
uploadImages();
return null;
}
#Override
protected void onPostExecute(Void res)
{
Log.d(TAG, "onPostExecute()");
pd.dismiss();
}
}.execute();
I'm using following code to fill a custom ListPreference dialog. Since the fill procedure takes a lot of time i want to show a progress dialog during the fill procedure.
My problem is that filler.execute() does not block onPrepareDialogBuilder and functions goes till the end before values are filled causing an exception... Any idea?
#Override
protected void onPrepareDialogBuilder(Builder builder) {
// Load data
if (this.getEntries()==null) {
FillerTask filler = new FillerTask();
filler.execute();
}
Log.d(TAG, "Filler finished");
super.onPrepareDialogBuilder(builder);
}
Here is Filltertask code, basically he looks for every activity with a MAIN Intent filling a list:
private class FillerTask extends AsyncTask<Void, Void, String[][]> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
Log.d(TAG, "Dismiss dialog");
dialog = ProgressDialog.show(MyListPreference.this.getContext(), "", "Doing stuff...", true);
}
#Override
protected String[][] doInBackground(Void... params) {
return fill();
}
public String[][] fill() {
Log.d(TAG, "Fill started");
CREATE LISTS...
// Done
Log.d(TAG, "Fill done");
String[][] result = new String[][] {entryNames, entryValues};
return result;
}
#Override
protected void onPostExecute(String[][] result) {
Log.d(TAG, "Post execute");
MyListPreference.this.setEntries(result[0]);
MyListPreference.this.setEntryValues(result[1]);
dialog.dismiss();
}
}
My problem is that filler.execute() does not block onPrepareDialogBuilder and functions goes till the end before values are filled causing an exception... Any idea?
That is the entire point behind an AsyncTask. The "Async" in AsyncTask means asynchronous.
Use your AsyncTask to get your data. Then, in onPostExecute(), display the dialog.
Found the solution, best way to do this is override the onClick method and let the AsyncTask postExecute call the "super()", so click is not passed until content is loaded and during load progress bar is correctly displayed.
asyntask doesn't lock main thread, it just drops a message to message queue of main thread