ProgressDialog is not updating in Async task - android

Could anyone explain why my progress dialog is not updating when my async task is running?
The progress dialog appears, but the percentage indicator does not increase at all.
Is there something obvious here?
private class DownloadFilesTask extends AsyncTask<ArrayList<String>, Integer, Long> {
private ProgressDialog mProgress;
#Override
protected void onPreExecute()
{
mProgress = new ProgressDialog(HelloActivity.this);
mProgress.setMessage("Fetching Image data..");
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setCancelable(false);
//mProgress.setIndeterminate(false);
mProgress.show();
}
#Override
protected Long doInBackground(ArrayList<String>... urls) {
long totalSize = 0;
for(int i=0; i < dbLinks.size(); i++){
try {
....doe some stuff here
publishProgress((i/dbLinks.size()) * 100);
} catch (DbxException e) {
e.printStackTrace();
}
}
return totalSize;
}
#Override
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
}
#Override
protected void onPostExecute(Long result) {
mProgress.dismiss();
//use totalsize if necessary
Intent intentFB = new Intent(HelloActivity.this, PostActivity.class);
intentFB.putExtra("key", dbURLs);
startActivity(intentFB);
}
}

Integer math.
(i/dbLinks.size()) * 100
i/dbLinks.size() will be always 0 and multiplying it by 100 doesn't change it.
To fix it, consider setting progress bar max to dbLinks.size() and publish i as progress.

You may be getting the exception in your doInBackground method ,as i check sample demo it is working fine.
private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
private ProgressDialog mProgress;
#Override
protected void onPreExecute()
{
mProgress = new ProgressDialog(MainActivity.this);
mProgress.setMessage("Fetching Image data..");
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setCancelable(false);
//mProgress.setIndeterminate(false);
mProgress.show();
}
#Override
protected Long doInBackground(String... progress) {
long totalSize = 0;
for(int i=0; i < 100; i++){
try {
publishProgress(i);
} catch (Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return totalSize;
}
#Override
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
}
#Override
protected void onPostExecute(Long result) {
mProgress.dismiss();
}
}

Related

ProgressBar into AsyncTask without xml

As the ProgressDialog is deprecated, I want to change this with a ProgressBar.
I wrote this code for a "MyAsyncTask", so this isn't connected to any xml file, but I can't see the ProgressBar.
public class MyAsyncTask extends AsyncTask<String, String, String> {
private ProgressBar pb;
public MyAsyncTask(AsyncResponse listener, Context context) {
this.pb = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
}
#Override
protected void onPreExecute() {
pb.setMax(100);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
for (; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(String... values) {
pb.setProgress(Integer.parseInt(values[0]));
}
#Override
protected void onPostExecute(String result) {
listener.onTaskCompleted(result);
pb.setVisibility(View.GONE);
}
}
Is it necessary to create an XML file?

Android progress bar for method

I have a custom method of my class that (on my Android phone) takes 2-3 second to finish, and I would like to surround it with a progress bar.
Here is my method:
public void getQuestionsForSelectedCategory(){
ArrayList<Question> temp = (ArrayList<Question>) this.clone();
ArrayList<Question> tempGroup;
this.clear();
for(int i=0;i<2;i++){
tempGroup = new ArrayList<Question>();
for(int j=0;j<temp.size();j++)
if((temp.get(j).getGroup()==i+1)&&(temp.get(j).getCategory().contains(category)||temp.get(j).getCategory().equals("*")))
tempGroup.add(temp.get(j));
getQuestionsForSelectedGroup(tempGroup, numbersByGroup[i], pointsByGroup[i]);
}
tempGroup = new ArrayList<Question>();
for(int i=0;i<temp.size();i++){
int a = temp.get(i).getGroup();
if((a==3||a==4||a==5||a==6||a==7))
if(temp.get(i).getCategory().contains(category)||temp.get(i).getCategory().equals("*"))
tempGroup.add(temp.get(i));
}
Collections.shuffle(tempGroup);
getQuestionsForSelectedGroup(tempGroup, numbersByGroup[2], pointsByGroup[2]);
if(category.equals("C")){
tempGroup = new ArrayList<Question>();
for(int i=0;i<temp.size();i++)
if(temp.get(i).getCategory().equals(category))
tempGroup.add(temp.get(i));
getQuestionsForSelectedGroup(tempGroup, 10, 30);
}
}
And here is what I try to do:
barProgressDialog = new ProgressDialog(this);
barProgressDialog.setTitle("Preparing Test");
barProgressDialog.setMessage("Preparing Test");
barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
barProgressDialog.setProgress(0);
barProgressDialog.setMax(100);
barProgressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
getQuestionsForSelectedCategory();
while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {
updateBarHandler.post(new Runnable() {
public void run() {
barProgressDialog.incrementProgressBy(2);
}
});
if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
barProgressDialog.dismiss();
}
}
} catch (Exception e) {
}
}
}).start();
}
For the current code the progress bar fills up to 100 but it does nothing.
You could use an AsyncTask to achieve this, whilst publishing your progress during the task.
AsyncTask<Void, Integer, Void> task = new AsyncTask<Void, Integer, Void>() {
#Override
protected Void doInBackground(Void... voids) {
getQuestionsForSelectedCategory();
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
barProgressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void aVoid) {
barProgressDialog.dismiss();
}
}
task.execute();
Ensure your getQuestionsForSelectedCategory and getQuestionsForSelectedGroup methods are inside the AsyncTask and within the loops you can call publishProgress(int progress) to update the progress dialog.

asyncTask value not passing

When I retrieve the value in results activity. I get nothing, I guess the the value is not being passed from doInBackground to onPostExecute. Any idea what's wrong? or am I passing it the wrong way
class calculateTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
Thread t= new Thread();
try {
t.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int pix=0;
int circ=0;
int width1=mBitmap.getWidth();
int height1=mBitmap.getHeight();
for(int i=0;i<width1;i++)
{
for(int j=0;j<height1;j++)
{
if(mBitmap.getPixel(i, j)==Color.WHITE)
{
pix++;
}
if(mBitmap.getPixel(i, j)==Color.LTGRAY)
{
circ++;
}
}
}
int percentage=100-((pix-circ))*100 ;
String p=intToChar(array,percentage);
return p;
}
#Override
protected void onPostExecute(String p) {
Intent i= new Intent(circle1.this,results.class);
i.putExtra("perc", p);
startActivity(i);
//super.onPostExecute(result);
}
}
public String intToChar(char[] array, int pix) {
// TODO Auto-generated method stub
String b="";
int i = array.length - 1;
while (pix > 0 && i >= 0) {
array[i--] = (char) (48 + pix % 10);
pix /= 10;
} b = new String(array);
return b;
}
I would use a global variable. Then assign value to the global variable in doInBackground, and then retrieve it in onPostExecute.
EDIT:
Many things are wrong.
Here is one of my examples from code
private class Load extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progressDialog;
private Context context;
private boolean internet, refresh;
public Load(Context context, boolean internet, boolean refresh)
{
this.internet = internet;
this.refresh = refresh;
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(context, null, "Loading data ...");
}
#Override
protected Void doInBackground(Void... voids)
{
taskComplete = false;
while (!taskComplete)
{
getData(this.internet);
try
{
Thread.sleep( 1000 );
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
populateData();
progressDialog.dismiss();
}
}
Try imitating this. getData sets taskComplete to true once it is done.

How can I add a progress dialog in AsyncTask with minimum loading time (2sec)

When user clicks button, will go to Activity B from Activity A.
However, since in Activity B, data will be downloaded from Internet, I would like to add a progress dialog.
Sometimes, the connection will be very fast, less than one second and sometimes will be more than 5 seconds.
If the progress dialog shows <1 sec, I think it is very bad for user experience.
So, I would like to add a minimum loading time, for example, 2 seconds.
That means even the loading time is less than 2 seconds, the progress dialog will also at least show 2 seconds.
Is there any ways to do so?
you can use Below Code. Pass Time and Object of your Dialog here.
public void timerDelayRemoveDialog(long time, final Dialog d){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
d.dismiss();
}
}, time);
}
EDITED
you can Use this Sample Code :
class LoginProgressTask extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(4000); // Do your real work here
} catch (InterruptedException e) {
e.printStackTrace();
}
return Boolean.TRUE; // Return your real result here
}
#Override
protected void onPreExecute() {
showDialog(AUTHORIZING_DIALOG);
}
#Override
protected void onPostExecute(Boolean result) {
// result is the value returned from doInBackground
removeDialog(AUTHORIZING_DIALOG);
Intent i = new Intent(HelloAndroid.this, LandingActivity.class);
startActivity(i);
}
}
My solution (worked well):
private class ProgressTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
long timestamp1;
long timestamp2;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(YOUR_CONTEXT);
dialog.setCancelable(false);
dialog.setMessage("Please wait...");
dialog.show();
timestamp1 = System.currentTimeMillis();
}
#Override
protected Void doInBackground(Void... params) {
//doSomething ...
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//doSomething ...
timestamp2 = System.currentTimeMillis();
long timeDifference = timestamp2 - timestamp1;
if (timeDifference >= 2000) {
dialog.dismiss();
} else {
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
dialog.dismiss();
}
}, 2000 - timeDifference);
}
}
}
Here is another version. Using SystemClock does not require try catch block.
ParentActivity.this is the context where Task is executed.
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.SystemClock;
protected class Task extends AsyncTask< String, Void, String >
{
private ProgressDialog mDialog = new ProgressDialog( ParentActivity.this );
private long mTaskStartTimeMills;
protected void onPreExecute()
{
mTaskStartTimeMills = System.currentTimeMillis();
mDialog.setMessage( "Loading.." );
mDialog.show();
}
protected String doInBackground( String... arg )
{
// TODO
return null;
}
protected void onPostExecute( String json )
{
final long timeToWait = 1000 - ( System.currentTimeMillis() - mTaskStartTimeMills );
if ( timeToWait > 0 )
{
SystemClock.sleep( timeToWait );
}
mDialog.dismiss();
}
}
this may helps you
new AsyncTask<Void, Void, Void>() {
ProgressDialog mDialog;
ArrayList<String> files;
#Override
protected void onPreExecute() {
mDialog = new ProgressDialog(MyMainAct.this);
mDialog.setMessage("Loading");
mDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// do your work here
Log.i("Share Media MyMainAct", " newFiles is called path is - " + path +"/" + spndirectory.getSelectedItem().toString());
files = getFiles(path + "/" + spndirectory.getSelectedItem().toString());
return null;
}
#Override
protected void onPostExecute(Void result){
if (mDialog != null && mDialog.isShowing()){
mDialog.dismiss();
}
setFileAdapter(files);
}
}.execute();

Android add a loading view to an AysncTask

Hi there i have an Asynctask that wroks only problem is the screen is blank until everything has loaded so i have created a loadingcell view but i'm wanting to know how to have it show the loading view until everything is loaded.
here what i have tried but it doesn't work
public class PostTask extends AsyncTask<Void, String, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
boolean result = false;
loadFixtures();
publishProgress("progress");
loadResultsFeed();
publishProgress("progress");
loadNewsFeed();
publishProgress("progress");
return result;
}
protected void onProgressUpdate(String... progress) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < progress.length; i++) {
str.append(progress[i] + " ");
loadingView = LayoutInflater.from(getBaseContext()).inflate(R.layout.loadingcell,
null);
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.v("BGThread", "begin fillin data");
FillData();
}
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.v("BGThread", "begin fillin data");
FillData();
// hide your view here <---------
// for ex:
progressbar.setVisibility(View.GONE); <---------
}
I have done this way. You can refer
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
downloadFile(b.getString("URL"));
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(ShowDescription.this,
"File successfully downloaded", Toast.LENGTH_LONG)
.show();
imgDownload.setVisibility(8);
} else {
Toast.makeText(ShowDescription.this, "Error", Toast.LENGTH_LONG)
.show();
}
}
}
Try this.
private class BackgroundTask1 extends
AsyncTask<String, Void, String> {
private ProgressDialog dialog;
protected void onPreExecute() {
/** Initialise progress dialog and show*/
dialog = new ProgressDialog(currentActivity.this);
dialog.setMessage("Loading.....");
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(final String... args) {
// do your stuff
return anyString // as an example
}
protected void onPostExecute(String temp) {
Log.v("String:::::",temp);
dialog.dismiss(); // dismiss progress dialog
}
}

Categories

Resources