Progress dialog during tab switch - java

When the user switches from tab A to tab B it takes a long time (6 seconds), so I put in a progress dialog to let the user know that the app is working on it. The timeline is as follows:
Activity B onCreate - creates ProgressDialog and puts long tasks in a background Thread.
Activity B onStart
Activity B onResume
Activity B appears on the screen
This all works great with one "minor" snafu- the app intermittently crashes because the onResume function references something that is created by the background Thread. It is, in other words, a classic race condition.
To fix the race condition I did a "join" on the thread right before the reference in onResume, but that makes the progress dialog not show up until the background thread is done (i.e. it shows up for a split second and then goes away) and the app acts like it is hung while the background thread is working. Apparently the progress dialog cannot show up until onResume completes.
My question is this: how can I get the ProgressDialog to show up without crashing the program? Or do I need to either get the offending reference out of onResume or live with the app acting hung?

I ended up using a kludgey solution wherein the onResume function waits for the intermediate result that it needs, but not for the entire background thread to finish. This is ugly, I know, but it appears to work.
The better long term solution, I believe, is to separate the creation of the needed object from the long initialization steps that it does when it is created. The timeline would then be:
onCreate
Create object
Create progress dialog
Create background thread, have it do long initialization of object.
onStart
onResume (with no check/sleep loop).

A dirty solution would be to have one ProgressDialog for steps 1 and 2, and then create a second identical-looking one for steps 3 and 4.

Are you using Threading as provided by the Java platform or are you using the Android convenience classes?
I am referring to AsyncTask. More than likely you are running in to issues with your Runnables posting at inconvenient times. The AsyncTask class packages up these features nicely. Subclass AsyncTask, specifying the types for your params, progress, and result. Then hide your dialog in the onPostExecute method, while you perform background work in the doInBackground method.
Sample code:
AsyncTask<Void, Void, Void> parseTask = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPostExecute(Void result) {
// Dismiss the progress dialog
dismissDialog(PROGRESS_DIALOG);
}
#Override
protected Void doInBackground(Void... params) {
// Do background work
return null;
}
};
// Start the background thread
parseTask.execute();
Taken from a live code base. Also don't feel too bad, concurrent programming is easily one of the more difficult systems to program. It is promising that you were able to recognize and identify the race condition.

Related

Android animation only works if I reschedule it from the UI thread to the UI thread

I perform a network call in which I
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
and then I pass the result to an io.reactivex.function.Consumer, which attempts to animate a view.
These animations worked when I was loading the data locally and synchronously, but broke when I introduced this server call.
Now when I animate the views, it does not change any of the properties at all, but instead just instantly calls the animation complete listener.
I verified that I'm on the main thread with Looper.getMainLooper().isCurrentThread()
Yet the only way I've been able to get the animation working again is to wrap it in AndroidSchedulers.mainThread().scheduleDirect(() -> {})
Which as shown by this piece of code shouldn't actually change anything
final Thread before = Thread.currentThread();
AndroidSchedulers.mainThread().scheduleDirect(() -> {
boolean nothingChanged = before == Thread.currentThread();
//nothingChanged is true
});
Why do I have to reschedule the animation back onto the thread it is already on in order to get it to work?
Edit: RxJava is not involved, something even weirder is going on.
I cut out RxJava and the issue is reproducing even though I put the animation code in onNavigationItemSelected(), which is called by android when the user clicks something, so its definitely in the right thread.
My animation looks like this.
alertBanner.clearAnimation();
alertBanner.animate()
.alpha(0)
.translationY(alertBanner.getHeight())
.setDuration(500)
.setListener(new AnimatorListenerBuilder().setOnAnimationEnd(animator -> {
alertBanner.setVisibility(GONE);
}))
.start();
AnimatorListenerBuilder is just a utility class that wraps AnimatorListener and lets you only define the callbacks that you want. It works for all the other animations in my app and hasn't been changed in months.
I figured it out. It was a race condition.
When the user clicked the button, two things happened:
A new fragment was created, and an animation was started.
However, the fragment had a callback, onAttach() that would, among other things, call .clearAnimation() on the view I was trying to animate.
By rescheduling the animation back onto the main thread, I was making sure that it happened after the fragment callback.
I solved it by getting rid of the callback from the fragment, and putting that logic in the same place as the logic that starts the animation, allowing me to control the execution order.

application crash aftet restarting an acticity several times

I have this wierd situation that i can't understand.
I developed an application on android studio, on the first activity i start a second activity, on that second activity i created a SurfaceView child class that extends surfaceView and implemment Runnable and draw on the canvas inside run(), when i exit the thread i call onRestart() to start the canvas thread again.
all good so far, i open the thread, draw some images in a loop, exit the thread loop, restart.
the problem is that after 20 times of restarting, the application crash with no logical reason.
what do you think the problem can be? how to check it and fix it?
this function is the thread work inside the surfaceView child class (of the activity)
#Override
public void run() {
while (!_susspendThread) {
// draw images
}
onRestart();
}
this function is on the parent activity class
protected void onRestart() {
// make some changes, nothing critical to the question
// examp. count++;
surface_view.StartThreadWork();
}
another thing i must say although i dont belive it's related to the problem is that onCreate i read some internal files.
thanks for any help.
You have a memory leak, and this could be from many things. A good place to begin, is to use the onDestroy() methods of your Activities to cleanup any resources you have generated (like the internal files you are creating in your onCreate method).
Also, there are tons of tools for tracking memory usage, in AndroidStudio (AS) there is a "Memory" tab in the "Android" view. Also, you can run the "Monitor" tool (available from the command-line, or within AS to get ton's of details on what type of resource you are leaking.

Suspend Android app's main thread while showing the ProgressDialog

When my Android app is starting up needs to load a lot of data from the database during onCreate in the firstly loaded activity. I would like to show a ProgressDialog for that. ProgressDialog however can't be shown in the main thread, so one must use AsyncTask or new Thread. But that also means, that the activity continues to be initialized as the main thread goes on.
Basically, I need to show the ProgressDialog or a kind of its equivalent while processing in the main thread (not in AsyncTask).
Is there a way to do it?
ProgressDialog however can't be shown in the main thread, so one must use AsyncTask or new Thread.
How do you come to this conclusion? ALL UI stuff is shown in the UI Thread, thus also the ProgressDialog. It needs to be created and invoked inside the UI Thread to work or else your App crashes.
First you need to check on onCreate() if your stuff is already loaded and if not, show a ProgressDialog, load stuff in the background and then do a post in the UI Thread to dismiss the ProgressDialog and show the results.
That's how it usually works.
The Main/UI Thread is responsible for drawing the UI, and hence, the ProgressDialog itself . So you can not block it and hope that he is going to draw the UI. You should move the initialization stuff inside AsyncTask's doInBackgroud, and move on with the other suff after onPostExecuted is called
You should load the the data with the Thread (ASyncTask) you should display your ProgressDialog with "onPreExecute()" update it with "onProgressUpdate()" and finish the dialog with "onPostExecute()" all of them is running on UI thread already.
You will never be able to show progress because your view of activity have not created, because you read from database in onCreate methode after reading the database onCreate method finshes and now your view inflate and so on . . .

Android View Canvas onDraw not performed

I am currently working on a custom View which draws some tiles on the canvas.
Those tiles are loaded from several files and will be loaded when needed.
They will be loaded by an AsyncTask. If they are already loaded they will just be painted on the canvas. This is working properly!
If those pictures are loaded the AsyncTask is firing view.postInvalidate()
The problem is that my custom View is not firing onDraw(Canvas canvas) everytime I fire view.postInvalidate().
The view.postInvalidate only fires onDraw() method the first time when a picture is loaded and then only when I fire this.invalidate() in an onTouchEvent inside my CustomView
Is it possible that a View decides wether it will draw the canvas again or not?
Is there a way to FORCE the View to redraw? I think the invalidate method tells the View that it would be cool if the View would think about redrawing -.-
Is it possible that those invalidate methods have a limit?
I hope anyone of you knows more about this problem.
edit:
I just changed every postInvalidate() to invalidate() because the images are all loaded by an AsyncTask executed from the main Thread
But there is still the problem that an executed invalidate() is not executing the onDraw() method.
I found out that the view.invalidate() is fired by overriding the original method:
#Override
public void invalidate() {
super.invalidate();
Log.d(TAG, "invalidate executed");
}
I don't know what to do now. I'm firing view.invalidate() and view.postInvalidate() but nothing works in absolutely no combination.
There's a bit of a misunderstanding here. The invalidate and postInvalidate method are used to tell the View that it needs to be refreshed and redrawn in the earliest drawing cycle. The difference is that the invalidate method should be called from within the UI Thread and the postInvalidate should be called from outside of the UI Thread.
These methods are briefly described here:
http://developer.android.com/reference/android/view/View.html#postInvalidate()
http://developer.android.com/reference/android/view/View.html#invalidate()
The AsyncTask on the other hand is a class devised especially for the problem you're facing. When you need to perform a big task in the background, asynchronously you need the AsyncTask for that, but! the AsyncTask's callback method is run in the UIThread!
Take a look at the explanation of AsyncTask methods here:
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), 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.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
This means that in the onPostExecute method you should try using the invalidate method instead of the postInvalidate method as it is called from the UIThread.
Have you heard of a method call setWillNotDraw(boolean)?
Check it out here
Set it to false and you'll see
Just to save this for the future and possible google searchers ;)
I made a new Class which provides datas for my View. This class extends Thread and runns in the background. It checks which tiles my view has to display.
Long story short: Each time a new tile has to be displayed my provider class collects some update requests.
If 3 or more update requests are "collected" or it is more than 1 second since the first update request the view will get view.postInvalidate().
The problem was that a view ignores some invalidate requests if you fire several of them at once. If you collect those invalidate requests and fire several of them with just one invalidate() you can see the newest information with just a small lag of time - but you can see it ;)
I've solved the problem requesting view.invalidate() or view.postInvalidate() not for invalidating every child view individually (each of these child views incorporated its own AsyncTask), but for invalidating their common parent ViewGroup.
Now in details. I had
public class mViewGroup extends RelativeLayout {...}
and several Views in it, each View as follows:
public class mView extends View {
private mViewGroup mContext = null;
//with a little bit modified standard constructors:
public mView (Context context, mViewGroup ParentViewGroup) {
super(context);
mContext = ParentViewGroup;
}
//and also with an AsyncTask:
private class mViewAsyncTask extends AsyncTask<Integer, Void, Void> {
public mAsyncTask() {
#Override
protected Void doInBackground(Integer... a) {
//which does its work and sometimes publishes progress:
publishProgress();
return null;
}
protected void onProgressUpdate(Void... progress) {
invalidate();
}
}
The calls to invalidate(); sometimes worked and sometimes didn't (may be in cases if calls were made from different AsyncTasks belonging to different mViews but in very close moments of time).
Changing
invalidate(); //i.e. invalidating individual View
to
mContext.invalidate(); //i.e. invalidating the whole ViewGroup
solved the problem.
In my case, target custom View has height = 0 attribute at that time.(My mistake)
and postInvalidate() and invalidate didn't fired onDraw() and Log too.
When I changed height currectly, all problem solved.

How to handle progress dialog correctly in android?

I am new in android and java. I am in a trouble in implementing progress dialog correctly.
I have a code like this
ProgressDialog dialog= new ProgressDialog(Main.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
MY METHOD WHICH GRABS DATA FROM INTERNET;
dialog.dissmiss();
but by implementing this, my method runs well but no progress dialog is visible, again when i comment out the dismiss method, the dialog doesnt stop and i had to force close the app,then how to use this dialog? in aditional dont want to bring any thread here, is there any way to use dialog without any thread? Thanks
Problem here is that any long running tasks such as fetching data from the Internet must be run inside a separate thread, otherwise you're likely to get an ANR if your code runs for more then 5 seconds. The ideal solution in my opinion is to implement an AsyncTask: it lets you run tasks in a separate thread and helps you easily update your UI thread, showing ProgressDialogs or ProgressBars to let your users know that your app is currently busy. Simply place all your ProgressDialog initialization code inside the onPreExecute() method of the AsyncTask, and the dialog.dismiss() call to onPostExecute(). Hope this helps.
Yes, you no need to use Thread class. You can use AsyncTask instead. Start the progress dialog when you call the AsyncTask, dismiss it in the postExecute method.
I personally prefer AsyncTask for progress dialog.
In your onPreExecute, create your above code. In doInBackground, do your background tasks and in onPostExecute display an alertdialog saying work done !

Categories