onProgressUpdate is not being called android - java

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

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!

Progress Dialog Shows but no Progress Bar Shows and Message Isn't Updating

I have this class that gets called from a fragment. On progress update gets called but the message will not update. I also am not seeing any progress bar or spinner. Just the title and the message, seen some similar problems but nothing where the progress bar isn't showing at all. Also, my message will not update at all in onProgressUpdate but printing out the values does show that it increments inside of the onProgressUpdate.
Edit: Here is how I start the task
DownloadFilesTask download = new DownloadFilesTask();
download.execute(urls.toArray(new String[urls.size()]));
Here is the class
private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(getActivity(), "Downloading","Downloaded 0/"+urls.size(), false);
progressDialog.setProgress(0);
progressDialog.setMax(urls.size());
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected Long doInBackground(String[] urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
//Do things in background here
publishProgress(new Integer[] {i});
}
return totalSize;
}
#Override
protected void onProgressUpdate(final Integer... progress) {
System.out.println(progress[0]); //This does print correctly
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.setProgress(progress[0]);
progressDialog.setMessage("Downloaded "+ progress[0] +"/"+urls.size());
}
});
}
#Override
protected void onPostExecute(Long result) {
progressDialog.dismiss();
Toast t = Toast.makeText(getActivity(), "Downloaded", Toast.LENGTH_LONG);
t.show();
}
}
The issue is with the way your ProgressDialog is initialized.
Replace your onPreExecute with this:
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(activity);
progressDialog.setTitle("Downloading");
progressDialog.setMessage("Downloaded 0/" + urls.size());
progressDialog.setIndeterminate(false);
progressDialog.setProgress(0);
progressDialog.setMax(urls.size());
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
Essentially, you need to call setProgressStyle before calling show.
Additionally, you can remove the runOnUiThread code in onProgressUpdate because onProgressUpdate is invoked on the UI thread.
Not sure of the exact cause, but it is not required to setProgress on runnable as onProgressUpdate will run on UI thread.
Try Replacing
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.setProgress(progress[0]);
progressDialog.setMessage("Downloaded "+ progress[0] +"/"+urls.size());
}
});
with
progressDialog.setProgress(progress[0]);
progressDialog.setMessage("Downloaded "+ progress[0] +"/"+urls.size());
Also - Are you doing networking stuff in doInbackground(), else we cannot see progress which will be dismissed on onPostExecute().

Progress dialog async task taking longer time than expected

I am new to android programming. I am developing a web crawler for which i am using a Async Task and it is working well.In order to keep user informed,i am using progress dialog. My problem is,if i use a Progress Dialog my program takes more time to execute and when i won`t use the progress dialog,it executes faster.
Done Work
OnCreate Method
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
Intent intent = getIntent();
s1 = intent.getStringExtra("Number1");
s2 = intent.getStringExtra("Number2");
s3=intent.getIntExtra("selectedItem",0);
HttpAsyncTask asyncTask = new HttpAsyncTask();
asyncTask.execute();
}catch (Exception e)
{
messageBox("Exception",e.getMessage());
}
}
Async Task Class
private class HttpAsyncTask extends AsyncTask<List<String>, Integer, List<String>> {
private ProgressDialog dialog;
#Override
protected void onPreExecute()
{
dialog = new ProgressDialog(Results.this);
dialog.setIndeterminate(true);
dialog.setMessage("Please Wait");
dialog.setCancelable(true);
dialog.show();
super.onPreExecute();
}
#Override
protected List<String> doInBackground(List<String>... urls) {
//android.os.Debug.waitForDebugger();
// spinner.setVisibility(View.VISIBLE);
List<String>resultList=new ArrayList<String>();
try
{
if(isCancelled())
return resultList;
resultList=WebCrawlerClass.GetPost(s1,s2,s3);
}catch (Exception e)
{
messageBoxs("Error", e.getMessage());
}
return resultList;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(List<String> result)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
if(s3 == 2)
{
docListAdapter=new ListViewData(Results.this,result);
}
else {
docListAdapter = new NameNumListData(Results.this, result);
}
docList=(ListView)findViewById(R.id.listView2);
docList.setAdapter(docListAdapter);
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
super.onCancelled();
this.cancel(true);
}
}
Am I missing something? Need help..
Thanks and Regards,
Abhinav
In you activity
// Start the progress dialog
..
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// dismiss the progress dialog
}
};
HttpAsyncTask asyncTask = new HttpAsyncTask(handler);
asyncTask.execute();
In your asynctask class
private class HttpAsyncTask extends AsyncTask<List<String>, Integer, List<String>> {
private Handler handler = null;
public HttpAsyncTask (Handler handler) {
this.handler = handler;
}
protected Void doInBackground(Void... params) {
//Perform your task
// When you know that task is finished , fire following code
if (null != handler) {
Message message = handler.obtainMessage();
message.obj = Any data you want to sent to the activity
message.what = 1 ; ( Optional )
handler.sendMessage(message);
}
}
Thus when sendMessage function is called from doInbackground.. your handleMessage in your activity will get triggered and then you should dismiss the progress dialog
Hope this will improve the performance issue what you are facing
Remove super.onPreExecute(); in onPreExecute() method and check .It might Help

Errors canceling AsyncTask "Cannot make a static reference to the non-static method cancel(boolean) from the type AsyncTask<Void,Integer,Void>"

I am trying to make it so that when the user pushes a button than it cancels the Asynk task and then finishes the activity but i keep getting errors with the "MyAsyncTask.cancel(true);" if there is additional info you need please tell me.
here is what I got,
class MyAsyncTask extends AsyncTask<Void, Integer, Void>{
boolean DoingSomething;
int progress_status;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.v("UpGradeRep", "started");
DoingSomething = true;
UpGradeRep.setVisibility(View.GONE);
UpGradeRepDis.setVisibility(View.GONE);
Toast.makeText(MainActivity.this,
"started", Toast.LENGTH_SHORT).show();
// progress_status = 0;
}
#Override
protected Void doInBackground(Void... params) {
while (!isCancelled()) {
while(DoUpCount==true){
progress_status += 1;
publishProgress(progress_status);
SystemClock.sleep(200);
if(isCancelled()){
break;
}
}
}
return null;
}
int UpGradRepcounter = 0;
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
UpGradRepcounter++;
DevUpCountDis.setText(" "+UpGradRepcounter);
Money = Money +inc;
MoneyDis.setText("$"+Money);
}
#Override
protected void onCancelled() {
Toast.makeText(getApplicationContext(), "Canceled", Toast.LENGTH_SHORT);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
DoUpCount=false;
DoingSomething = false;
Log.v("UpGradeRep", "Done");
}
}
here's what i do when i am trying to close it
Statistics.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MyAsyncTask.cancel(true);
//^^^^Right here is where it tells me "Cannot make a static reference to the non-static method cancel(boolean) from the type AsyncTask<Void,Integer,Void>"
Intent GoToStatistics = new Intent(getApplicationContext(),statistics.class);
GoToStatistics.putExtra("LittleHelper", LittleHelper);
startActivity(GoToStatistics);
finish();
}
});
so thats the code i set up to do what i whant and it dose good but when i leave it gives a frame drop warning in my Logcat so i was ausuming that im not closeing it properly
im starting it like this
so when the user pushes the button than it starts it
UpGradeRep.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (Money>=upGM2) {
LittleHelper=true;
DoUpCount=true;
Log.v("DoUpCount"," "+DoUpCount);
(new MyAsyncTask()).execute();
}else{
Error.setText("you need more money.");
}
}
});
You're trying to call a metod over a non-static object within a static context (the onClick()) event. Basically what that error is telling you is that you must make your AsyncTask object static in order to be able to call the cancel() method over it.
This is as "easy" as declaring your AsyncTask as static, but that could generate some other compilation errors over your AsyncTask object, and you'll have to be very thorough to avoid possible memory leaks.
The method cancel(boolean mayInterruptIfRunning) (in class AsyncTask) is not a static method and you're calling it with the class name (the way static methods are invoked).
You should use the instance of MyAsyncTask to call (this):
this.cancel(true);

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

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().

Categories