Running progress bar while another task is being run android - android

I have an activity class where when a button is clicked i calls a function which updates some data. Below is the function
"startDIImport"
This function internally uses Thread.sleep(10000) to wait for another task to be completed.
Hence while this function is in progress i am planning to show a progress bar.
"showProgress" is the function which shows the progress bar.
I have written below code to show progress bar while my task runs in oncreate function
new Thread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
showProgress();
}
});
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
startDIImport();
}
}).start();
But my progressbar hangs when i click the button. Can you please help in resolving this issue.
I have checked AsyncTask but came to know that this has to be used only if the background task runs for few seconds. My background task may run to few hours.
Can you please let me know the best solution to handle this.

Use this code to run code on the ui thread. Also, you should never Thread.sleep(), use a proper callback mechanism instead. Show more code, it's hard to see what you're trying to do.
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
showProgress();
}
});

Related

java - Can I call a Async task inside a runnable postdelayed?

I have done a counter, who handler a limit time for my loading.
Its something like: If the process spend 10s, and my loading minimum time is 15s, this counter will execute a postdelayed with 5s.
But something is wrong, cause my app is crashing.
Here is what Ive done so far, in resume:
new MyHandler(secondsLeft, new LoadingFinishedCallBack() {
#Override
public void timeFinished() {
//CALLING A ASYNC TASK HERE
}).execute();
class MyHandler {
public void execute(){
runnable = new Runnable() {
#Override
public void run() {
handler.removeCallbacks(runnable);
callback.onTimeLeftFinished();
}
};
handler.postDelayed(runnable,timeLeft);
}
}
But for some reason, my app is crashing when doInBackground is calling, inside the async task.
I dont know why, cuz the error log doesnt show anything.
Can you guys help me pls

Can Runnable be called immediately?

Is it possible to call Runnable without execute-ing it?
AsyncTask.execute(new Runnable() {
#Override
public void run() {
//TODO your background code
}
});
In iOS a closure can be executed, or just called like a method. In first case there is a small delay, other code chunk can come first to the loop, in second case right at the time when call is done code is Runnable is performed. How is it with Android?
Runnable runnable = new Runnable() {...}
runnable.run();
and if you need to be able to decide where to execute it depending on your current thread: UI or non-UI, you can do something like this
if (Looper.getMainLooper().isCurrentThread()) { ... } else { ... }
Some useful information can be found here Runnable

Progress Bar + Main Thread UI Update Wait for Thread to complete (Android Java)

I have been getting help to create a progress bar for my Android application. Lots of help here! I'm having an issue though that I am having a hard time fixing. I have a progress bar shown while the application attempts to download files from a networked computer. This works perfectly fine, however I need to update my UI incase an error occurs. I can't update the UI inside the thread and I want to update the UI from getRaceResultsHandler. Unfortunately it executes that code prior to the thread being completed. I have tried a few things with no luck. I have a code sample with my comments below if anyone can help.
public void getRaceResultsHandler (View view) {
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Attempting to transfer race files. Please wait...");
// Set progress style to spinner
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// display the progressbar
dialog.show();
// create a thread for downloading the files
Thread background = new Thread (new Runnable() {
public void run() {
//The Code here to execute the file download from the networked computer....
//Dismiss the progress bar because the download is either completed or failed...
dialog.dismiss();
}
});
// start the background thread
background.start();
//All Other Code Goes here to update the UI. Shows either an error message or a success based on the results of the download.
//My problem is that this code executes before the background thread is completed. I need it to wait until the thread is completed.
}
Try to dismiss that dialog using Handler
Handler h = new Handler(); // Create this object in UI Thread
Thread background = new Thread (new Runnable() {
public void run() {
h.post(new Runnable()
{
public void run()
{
dialog.dismiss();
}
};
});
You should use AsyncTask instead of normal Thread
AsyncTask<Void,Void,Void> aTask = new AsyncTask<Void,Void,Void>()
{
#Override
public void onPreExecute()
{
// Setup some UI Objects
}
#Override
public void onPostExecute(Void result)
{
dialog.dismiss();
}
#Override
protected Void doInBackground(Void...params)
{
// your download stuff
publishProgress(object) // <-- if you want to update the progress of your download task
}
});
Note: Didn't try my own, have no IDE here in my friend's laptop

how to change UI element in a new thread task.onDone()?

How can I make this happend?
Thread t = new Thread(new Runnable() {
#Override
public void run() {
FacebookConnectTask task =
new FacebookConnectTask("facebookId", "token", "email", facebookGender,0, 0);
task.setOnPreExecuteListener(this);
task.setOnDoneListener(this);
task.execute();
}
});
t.start();
public void onPreExecute() {
progressbar.setVisibility(View.VISIBLE);
}
public void onDone() {
progressbar.setVisibility(View.GONE);
}
Since I am opening a new thread, I can not change a UI element in it, so, How can I manage to do something to the UI, when the task starts and when it's finished?
You could do the work in an AyncTask. The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.
preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.
More here: http://developer.android.com/reference/android/os/AsyncTask.html
Example here: http://www.vogella.com/articles/AndroidPerformance/article.html
inside your activity
private Handler myHandler=new Handler();
next in your on done callback
public void onDone() {
myHandler.post(new Runnable(){
#Override
public void run() {
progressbar.setVisibility(View.GONE)
}
})
}
But as already was said. AsyncTask is more siutable for it

android preference activity

I have a preference activity and want that if one of its items is clicked it will start a background work and show a nice progress bar in foreground until the background task finishes. how to do it???
Code writtenis:
public boolean onPreferenceClick(Preference preference) {
showProgressDialog();
new Thread(new Runnable() {
public void run() {
doSomething();
hideProgressDialog();
} //Runnable.run()
}).start();
return false;
}
});
But the above code is not showing progress dialog. and ANR error occurs.
Thanks.
Add following code in your activity class:
// Need handler for callbacks to UI Threads
// For background operations
final Handler mHandler = new Handler();
// Create Runnable for posting results
final Runnable mUpdateDone = new Runnable() {
public void run() {
progDialog.hide();
// Do your task here what you want after the background task is finished.
}
};
Write following code in onPreferenceClick:
progDialog = ProgressDialog.show(AddPhoto.this, "", "Uploading Photo...");
new Thread() {
public void run() {
// Start your task here.....
mHandler.post(mUpdateDone);
}
}.start();
Let me know if doesn't work for you!
I have not implemented a progress dialog yet (plan to later today), but this example looks like a good one. I plan to use it myself. I note that it does a number of things that your code does not.

Categories

Resources