Async Task and Progress Bar - android

I have two async tasks. Let's say A and B. A is first executed and on the post executed B is called. Now I need to show the progress bar after Task B ends. Like a percentage from 0 starting A and 100 endings of B. How can this be done?

in your onPreExecute and onProgressUpdate from asynctask A :
#Override
protected void onPreExecute() {
super.onPreExecute();
//show progress bar
}
#Override
protected void onProgressUpdate(Integer... progress) {
ProgressBar.setProgress(progress[0]/2)//we will take only 50% of the progress
}
in your onPostExecute and onProgressUpdate in your asynctask B
#Override
protected void onProgressUpdate(Integer... progress) {
ProgressBar.setProgress(progress[0]/2)//we will take the other 50% of the progress
}
#Override
protected void onPostExecute(String result){
//hide progress here
}
please make sure to make your progress bar local so you can access it from both asynctask

Within AsyncTasks you can update the UI on onProgressUpdate or onPostExecute callbacks. These two callbacks run in the main (UI) thread, whereas doInBackground runs in a worker thread.
In order to make the the "B" progress bar showing after the completion of AsynctaskA I would start the AsyncTaskB in the onPostExecute callback of AsyncTaskA, then update the progress bar B in its onProgressUpdate callback
public ProgressBar progressBarA = ProgressBar(this); // init with a progress bar coming from the UI here
public ProgressBar progressBarB = ProgressBar(this); // init with a progress bar coming from the UI here
private class AsyncTaskA extends AsyncTask<Void, Integer, Boolean> {
protected Boolean doInBackground(Void... params) {
// do something in the background here
for (int i = 0; i < 100; i++) {
publishProgress(i);
}
return true;
}
protected void onProgressUpdate(Integer... progress) {
progressBarA.setProgress(progress[0]);
}
protected void onPostExecute(Void result) {
AsyncTaskB taskB = new AsyncTaskB();
taskB.execute();
}
}
private class AsyncTaskB extends AsyncTask<Void, Integer, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBarB.setProgress(0);
}
protected Boolean doInBackground(Void... params) {
// do something in the background here
for (int i = 0; i < 100; i++) {
publishProgress(i);
}
return true;
}
protected void onProgressUpdate(Integer... progress) {
progressBarB.setProgress(progress[0]);
}
protected void onPostExecute(Void result) {
// Toast work complete!
}
}

Related

Upadate progressdialog message

I have one AsyncTask and I am setting message of ProgressDialog within onPreExecute() method. Now I want to update message of ProgressDialog within method which is called from StartUpload() method of doInbackground.
class performBackgroundtask extends AsyncTask<Void, Void, Void> {
// #Override
public void onPreExecute()
{
connectionProgressDialog = new ProgressDialog(ProcessReportsUploadActivity.this);
connectionProgressDialog.setCancelable(false);
connectionProgressDialog.setCanceledOnTouchOutside(false);
connectionProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
connectionProgressDialog.setMessage("Uploading data...");
connectionProgressDialog.show();
}
// #Override
public Void doInBackground(Void... params)
{
try
{
StartUpload();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
// #Override
public void onPostExecute(Void result)
{
connectionProgressDialog.dismiss();
connectionProgressDialog.cancel();
}
}
use publish progress in DoInBackground
publishProgress(""+(int)((total*100)/lenghtOfFile));
and update progess bar in onProgressUpdate
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
you can use onProgressUpdate
invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
#Override
protected void onProgressUpdate(Integer... progress) {
// setProgressPercent(progress[0]);
//set prograss to your prograss dialoglike this
connectionProgressDialog.SetProgress(progress);
}

How I can make some action on screen even if progress dialog is loading. Android

I am displaying progress dialog box on screen,
I can not make any action until the dialog got dismissed.
How can I make some action (like Clicking on button) on screen even if progress dialog box is loading.
Loading should not stop when I click on any of button.
Here is my AsyncTask:
//My Progress Dialog
progress = ProgressDialog.show(DefaultMarketWatch.this, "",
"Loading", true);
// My AsyncTask, Which executes for every 1 sec.
public class RetriveStock extends AsyncTask<Void, Void, ArrayList<User>> {
#Override
protected ArrayList<User> doInBackground(Void... params) {
message += client.clientReceive(1); // Receives data from TCP socket.
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
protected void onPostExecute(ArrayList<User> result) {
progress.dismiss(); // Dismissing my progress dialog
// My UI updations and all using "message" string.
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Please help..
Simply use AsyncTask for getting that data.
Don't use any progress dialog for showing progress.
AsyncTask will run on background not on UI thread so it will not hurdle any of your process while you are fetching or uploading any data.
Try this...
#Override
protected Void doInBackground(Void... params)
{
publishProgress(data to send on UI thread here );
return null;
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
// write your UI change code here This will perform on UI therad oh Activity
loading.setMessage("UI change");
}
If you want to do some action while loading the progress dialog means,You are violating the concept of the progress dialog.Because it is also an UI process.Better don't use the progress dialog.Use AsyncTask or runOnUIthread for your background data fetching event and do your stuff on UI.

Progress bar doesn't update

I created a Progress bar but I can't see the loading animation. It's frozen. I want to display a progress bar when I click on the item and then see the bar working and not frozen. Here is my code:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (((TextView) view).getText().equals("Zman-New (rus)")){
progDailog = ProgressDialog.show(testLoading.this, "Getting data", "Loading...",true,true);
new GetDataTask("stringurl.xml").execute();
}
Here is the getdata
private class GetDataTask extends AsyncTask<Void, Void, Integer> {
String url;
GetDataTask(String url){
this.url=url;
}
#Override
protected Integer doInBackground(Void... params) {
//do all your backgroundtasks
intent = new Intent(rusNewsP.testLoading.this, rusNewsTest.rusNewsActivite.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
return 1;
}
#Override
protected void onPostExecute(Integer result) {
//finish up ( or close the progressbar )
//do something with the result
progDailog.dismiss();
super.onPostExecute(result);
}
}
If you just want to test Progress try this:
private class Initialize extends AsyncTask<Short, Short, Short> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(yourlass.this);
pd.setMessage("test");
pd.show();
super.onPreExecute();
}
#Override
protected Short doInBackground(Short... params) {
try {
synchronized (this) {
wait(2000);
}
} catch (InterruptedException ex) {
}
return null;
}
#Override
protected void onPostExecute(Short result) {
pd.dismiss();
super.onPostExecute(result);
}
}
And don't call startActivity in the doInBackground-Method. Call it in OnPostExecute instead. GUI Operations should not be done in doInBackground.
Try to start the Activity Direct from the UI thread as that will be fast.
Still,if you want this way then try to start it from the onPostExecute Method.
Not from the doInBackground.
protected void onPostExecute(Integer result)
{
//do something with the result
progDailog.dismiss();
intent=new Intent(rusNewsP.testLoading.this,rusNewsTest.rusNewsActivite.class);
intent.putExtra("url",url);
startActivity(intent);
finish();
}
And...don't call super.onPostExecute(result); after dismissing the progressDialog..after completing the doInBackground(Short... params),It will return directly to onPostExecute Method where it will dismiss the ProgressDialog first time and then execute the Constructor which will try again to dismiss the ProgressDialog which is already dismissed resulting into uncaught exception.

Alert Dialog and ASync Task

i am trying to use Alert Dialog Box and Async Task in the activity and am getting the following error
Caused by: java.lang.RuntimeException: Can't create handler inside
thread that has not called Looper.prepare()
Code:
public class loginTask extends AsyncTask<Void, Void, Void> {
public ProgressDialog loginDialog = new ProgressDialog(
LoginActivity.this);
#Override
protected void onPreExecute() {
loginDialog.setMessage("Please wait Logging in");
loginDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
if(loginUser()) {
loginDialog.dismiss();
alertbox("title", "winnn", "Okay");
} else {
loginDialog.dismiss();
alertbox("title", "message", "Okay");
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
loginDialog.dismiss();
Intent intentHome = new Intent(LoginActivity.this,
HomeActivity.class);
startActivity(intentHome);
}
}
You can't update UI inside the doInBackground() method directly. (Yes if you still want to execute then write the same inside the runOnUiThread() method inside the doInBackground())
Otherwise, do it inside the onPostExecute() method.
public class loginTask extends AsyncTask<Void, Void, Void>
{
public ProgressDialog loginDialog = new ProgressDialog( LoginActivity.this );
public Boolean flag;
#Override
protected void onPreExecute() {
loginDialog.setMessage("Please wait Logging in");
loginDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
if(loginUser())
flag = true;
else
flag=false;
return null;
}
#Override
protected void onPostExecute(Void unused) {
loginDialog.dismiss();
if(flag)
alertbox("title", "winnn", "Okay");
else
alertbox("title", "message", "Okay");
}
}
the onPreexecute and onPostExecute are part of the UI parts in the Async Task.. the doInBackground is a seperate thread so any thing done inside the doInBackground needs to be handled in the form of progressUpdate
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Example Reference: Link
reflects any changes you need to make to the UI inbetween the doInBackground process.

Dismiss a dialog when a thread is done

I'm creating a thread in android for a time consuming operation. I want the main screen to show a progress dialog with a message informing that the operation is in progress, but I want that dialog to dismiss once the thread is done. I've tried with join but it locks the thread and doesn't show the dialog. I tried using:
dialog.show();
mythread.start();
dialog.dismiss();
but then the dialog doesn't show. How can I make that sequence but wait for the thread to end without locking the main thread?
This is as far as I got:
public class syncDataElcanPos extends AsyncTask<String, Integer, Void> {
ProgressDialog pDialog;
Context cont;
public syncDataElcanPos(Context ctx) {
cont=ctx;
}
protected void onPreExecute() {
pDialog = ProgressDialog.show(cont,cont.getString(R.string.sync), cont.getString(R.string.sync_complete), true);
}
protected Void doInBackground(String... parts) {
// blablabla...
return null;
}
protected void onProgressUpdate(Integer... item) {
pDialog.setProgress(item[0]); // just for possible bar in a future.
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
But when I try to execute it, it gives me an exception: "Unable to add window".
When your thread is done, use the runOnUIThread method to dismiss the dialog.
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
To do that there is two ways to do it , ( and i prefer the first second one : AsyncTask ) :
First : you display your alertDialog , and then on the method run() you should do like this
#override
public void run(){
//the code of your method run
//....
.
.
.
//at the end of your method run() , dismiss the dialog
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
Second : Using an AsyncTask like this :
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
//create and display your alert here
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Downloading data ...", true);
}
protected Void doInBackground(Void... unused) {
// here is the thread's work ( what is on your method run()
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
//dismiss the alert here where the thread has finished his work
pDialog.dismiss();
}
}
well in AsyncTask in the on postexecute you can call dismiss
here is an example from other thread
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true);
}
protected Void doInBackground(Void... unused) {
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}

Categories

Resources