Struggling to find issue with why AsyncTask is not being stopped by Handler - debugging

I am using this example:
Android - Setting a Timeout for an AsyncTask?
in the following way:
al.setOnClickListener(new OnClickListener(){
public void onClick(View w)
{
final AlogLoader loader = new AlogLoader();
loader.execute();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
if(loader.getStatus() == AsyncTask.Status.RUNNING)
{
loader.cancel(true);
}
}
}, 1);
}
});
I set it to "1" because I wanted to see if I can stop it practically before it even starts - to see if my handler is working - in reality I would probably set it to 15000 (15 seconds).
However what happens is confusing:
Running the application, causes my onPreExecute() to draw a loading screen, which doesn't ever exit, so the user just sees a loading screen perpetually.
Running it in the debugger with the breakpoint at loader.cancel(true) -> Causes the debugger to stop at that line, which is expected because its only allowed to run for 1 millisecond. However, when I hit the resume button in the debugger after that - my onPostExecute() is called... How is that possible?
Clearly, I'm very new to timing out asynctasks - after some research, I found the example above and it seemed to make the most sense to me, definitely more then
loader.get(15000, TimeUnit.MILLISECONDS);, since that blocks the UI Thread.
Any help is appreciated...even an explanation on the process..

Okay,
So I essentially solved my problem but I am still confused... Don't know if that's all good.
I was unclear on how loader.cancel(true) actually works. Based on the API level (read this question : AsyncTask.onCancelled() not being called after cancel(true)) you need to have an onCancelled() or onCancelled(params) method, or both in your AsyncTask.
I did not have this, so this explains why I saw a loading screen forever. Okay Good.
Yet, it doesn't explain how in the debugger, I managed to still call the onPostExecute(), because according to Android API's, onPostExecute is never called once cancel(true) has been called...
The answer is:
Add this to your AsyncTask-
#Override
protected void onCancelled()
{
Toast.makeText(FriendsActivity.this,"Blah- reason", Toast.LENGTH_LONG).show();
loadingScreen.dismiss();
}

Related

Xamarin.iOS: MobileService.InvokeApiAsync skips

I am developing an app using Xamarin.Forms to re-use as much code as possible.
Specifically, I have a static class that manages all the POST/GET requests to my Azure Web Server.
Everything single call works fantastically except for one call - this one:
public async static Task<Models.UserParkPosition> GetUserParkPositionForCurrentUserAsync()
{
var body = new JArray { App.User.Id };
var test = await AzureMobileServiceClient.Instance.MobileService.InvokeApiAsync<JArray, Models.UserParkPosition>(ConnectionsAPI, body, HttpMethod.Get, null);
return test;
}
The method above is called when the user presses a button - specifically like this:
private async Task OnGoingToTheParkClicked(object sender, EventArgs e)
{
bool success = false;
var already = await viewModel.AlreadyHavePendingRequestAsync());
Console.WriteLine("TEST");
throw new Exception();
}
When the debugger hits the "var test" line mentioned, above.... nothing happens. The code doesn't deadlock, the UI is still responsive, but the code never returns. I never see the "TEST" word and the exception is not even thrown... what happens??
All my other APIs are called in the same way, and are working correctly.
OTHER INFO:
- Same code works on UWP and Android
- The GET request arrives at the webservice, which responds in a timely fashion (< 1 sec)
Thanks to anyone who might help or even point me in the right direction!
Found the issue - InvokeApiAsync throws an exception which is not catched anywhere from any calling thread. It somehow just disappears without causing any error nor device log, nor crash. Weird, but that's how the world goes.

Why use Device.BeginInvokeOnMainThread() in a Xamarin application?

My code looks like this:
public void Init() {
if (AS.pti == PTI.UserInput)
{
AS.runCardTimer = false;
}
else
{
AS.runCardTimer = true;
Device.BeginInvokeOnMainThread(() => showCards().ContinueWith((arg) => { }));
}
}
The Init method is called from the constructor. Can someone please explain to me why the developer might have added the Device.BeginInvokeOnMainThread() instead of just calling the method showCards?
Also what does the ContinueWith((arg)) do and why would that be included?
The class where this Init() method is might be created on a background thread. I'm assuming showCards() are updating some kind of UI. UI can only be updated on the UI/Main thread. Device.BeginInvokeOnMainThread() ensures that the code inside the lambda is executed on the main thread.
ContinueWith() is a method which can be found on Task. If showCards() returns a task, ContinueWith() makes sure the task will complete before exiting the lambda.
UI actions must be performed on UI thread (different name for main thread). If you try to perform UI changes from non main thread, your application will crash. I think developer wanted to make sure it will work as intended.
The simple answer is: Background thread cannot modify UI elements because most UI operations in iOS and Android are not thread-safe; therefore, you need to invoke UI thread to execute the code that modifies UI such MyLabel.Text="New Text".
The detailed answer can be found in Xamarin document:
For iOS:
IOSPlatformServices.BeginInvokeOnMainThread() Method simply calls NSRunLoop.Main.BeginInvokeOnMainThread
public void BeginInvokeOnMainThread(Action action)
{
NSRunLoop.Main.BeginInvokeOnMainThread(action.Invoke);
}
https://developer.xamarin.com/api/member/Foundation.NSObject.BeginInvokeOnMainThread/p/ObjCRuntime.Selector/Foundation.NSObject/
You use this method from a thread to invoke the code in the specified object that is exposed with the specified selector in the UI thread. This is required for most operations that affect UIKit or AppKit as neither one of those APIs is thread safe.
The code is executed when the main thread goes back to its main loop for processing events.
For Android:
Many People think on Xamarin.Android BeginInvokeOnMainThread() method use Activity.runOnUiThread(), BUT this is NOT the case, and there is a difference between using runOnUiThread() and Handler.Post():
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);//<-- post message delays action until UI thread is scheduled to handle messages
} else {
action.run();//<--action is executed immediately if current running thread is UI thread.
}
}
The actual implementation of Xamarin.Android BeginInvokeOnMainThread() method can be found in AndroidPlatformServices.cs class
public void BeginInvokeOnMainThread(Action action)
{
if (s_handler == null || s_handler.Looper != Looper.MainLooper)
{
s_handler = new Handler(Looper.MainLooper);
}
s_handler.Post(action);
}
https://developer.android.com/reference/android/os/Handler.html#post(java.lang.Runnable)
As you can see, you action code is not executed immediately by Handler.Post(action). It is added to the Looper's message queue, and is handled when the UI thread's scheduled to handle its message.

UmbrellaException which contains ClassCastException when using GWTBootstrap3 Extras Summernote event handling (KeyUp Event)

I try to handle a Summernote Keyup event with this:
myEditor.addSummernoteKeyUpHandler(new SummernoteKeyUpHandler() {
#Override
public void onSummernoteKeyUp(final SummernoteKeyUpEvent event) {
// TODO Auto-generated method stub
log.fine("hello");
}
});
I get a UmbrellaException which is IMHO a class cast exception.
This is the call stack
I identified the following spot where te cast failes:
#HasNoSideEffects
static native boolean canCast(Object src, JavaScriptObject dstId) /*-{
if (#com.google.gwt.lang.Cast::instanceOfString(*)(src)) {
return !!#com.google.gwt.lang.Cast::stringCastMap[dstId];
} else if (src.#java.lang.Object::castableTypeMap) {
return !!src.#java.lang.Object::castableTypeMap[dstId]; //<-- this returns false!!!
} else if (#com.google.gwt.lang.Cast::instanceOfDouble(*)(src)) {
return !!#com.google.gwt.lang.Cast::doubleCastMap[dstId];
} else if (#com.google.gwt.lang.Cast::instanceOfBoolean(*)(src)) {
return !!#com.google.gwt.lang.Cast::booleanCastMap[dstId];
}
return false;
}-*/;
dstId contains:
Any help greatly appreciated!
I tested this with a small demo which actually works. But in my large application, I get this exception and I don't see why.
Do you have any idea whats wrong here?
Best regards
Hannes
As Andrei suggested I set the style to DETAILED. I use Eclipse as a development environment. I decided to clean build the system (which I had done before). Now the problem has simply vanished !! Furthermore, I use SDBG (see: https://sdbg.github.io/) to debug my GWT application. This works pretty well (even without -style DETAILED). Now the very very strange thing remains. I can set breakpoints for my application and they all work well, except setting a breakpoint within the event handling method. I use a logger to print some text to the console, so I see that the event handler for summernote is actually called but the debugger will not stop. I checked whether the breakpoint is listed in the tab "Breakpoints" and it is and it is checked. I don't get it. Perhaps I have to rebuild all again.
But to keep long things short:
The solution to the problem is probably to really issue a clean build and then hope for the best.

Switch Screens in BlackBerry

I have a BlackBerry App that has a Listener for the Send Button implemented in the CheckIn Screen. Data is sent through a web service. If the data is sent successfully, a confirmation message of "OK" is received. I am trying to switch screens in my BlackBerry App depending on the response received.
FieldChangeListener sendBtnListener = new FieldChangeListener() {
public void fieldChanged(Field field, int context)
{
try {
String alertMsg=sendTextCheckIn();
if(alertMsg.equals("OK"))
{
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen(new MyScreen());
}
} );
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
However, the above is throwing an App Error 104: IllegalStateException. Can anyone please guide on how to switch screens between a BlackBerry App.
EDIT: I can switch to any other screen but I CAN NOT switch to MyScreen. NOTE: MyScreen is the main (first) screen of the App. The above method sendTextCheckIn() calls another method that is placed inside MyScreen. Has this got anything to do with the error? Please advice.
The 'fieldChanged' event is already running on the UI event thread, so you shouldn't need to do the invokeLater call within it, just call pushScreen directly.
You mention that your problem with IllegalStateException only happens for MyScreen. That makes it sound like something specific with the implementation of MyScreen. Start narrowing down the problem - look at what happens in the constructor of MyScreen, and any events that might get called before the screen is visible. Some of that code is what is causing the problem.
Wrap everything that could possibly raise in exception in try/catch.
Don't do e.printStackTrace() - that won't give you much.
Instead do something like System.err.println ("KABOOM in method abc() - " + e); - seems like more effort, but trust me, that becomes INVALUABLE when debugging issues like this.
Catch Exception, unless you have a VERY good reason to catch a specific a subtype - otherwise you WILL end up with unexpected, and uncaught exceptions, which you will hunt for DAYS.

How can a JSF/ICEfaces component's parameters be updated immediately?

I have an ICEfaces web app which contains a component with a property linked to a backing bean variable. In theory, variable value is programmatically modified, and the component sees the change and updates its appearance/properties accordingly.
However, it seems that the change in variable isn't "noticed" by the component until the end of the JSF cycle (which, from my basic understanding, is the render response phase).
The problem is, I have a long file-copy operation to perform, and I would like the the inputText component to show a periodic status update. However, since the component is only updated at the render response phase, it doesn't show any output until the Java methods have finished executing, and it shows it all changes accumulated at once.
I have tried using FacesContext.getCurrentInstance().renderResponse() and other functions, such as PushRenderer.render(String ID) to force XmlHttpRequest to initialize early, but no matter what, the appearance of the component does not change until the Java code finishes executing.
One possible solution that comes to mind is to have an invisible button somewhere that is automatically "pressed" by the bean when step 1 of the long operation completes, and by clicking it, it calls step 2, and so on and so forth. It seems like it would work, but I don't want to spend time hacking together such an inelegant solution when I would hope that there is a more elegant solution built into JSF/ICEfaces.
Am I missing something, or is resorting to ugly hacks the only way to achieve the desired behavior?
Multithreading was the missing link, in conjunction with PushRenderer and PortableRenderer (see http://wiki.icesoft.org/display/ICE/Ajax+Push+-+APIs).
I now have three threads in my backing bean- one for executing the long operation, one for polling the status, and one "main" thread for spawning the new threads and returning UI control to the client browser.
Once the main thread kicks off both execution and polling threads, it terminates and it completes the original HTTP request. My PortableRenderer is declared as PortableRender portableRenderer; and in my init() method (called by the class constructor) contains:
PushRenderer.addCurrentSession("fullFormGroup");
portableRenderer = PushRenderer.getPortableRenderer();
For the threading part, I used implements Runnable on my class, and for handling multiple threads in a single class, I followed this StackOverflow post: How to deal with multiple threads in one class?
Here's some source code. I can't reveal the explicit source code I've used, but this is a boiled-down version that doesn't reveal any confidential information. I haven't tested it, and I wrote it in gedit so it might have a syntax error or two, but it should at least get you started in the right direction.
public void init()
{
// This method is called by the constructor.
// It doesn't matter where you define the PortableRenderer, as long as it's before it's used.
PushRenderer.addCurrentSession("fullFormGroup");
portableRenderer = PushRenderer.getPortableRenderer();
}
public void someBeanMethod(ActionEvent evt)
{
// This is a backing bean method called by some UI event (e.g. clicking a button)
// Since it is part of a JSF/HTTP request, you cannot call portableRenderer.render
copyExecuting = true;
// Create a status thread and start it
Thread statusThread = new Thread(new Runnable() {
public void run() {
try {
// message and progress are both linked to components, which change on a portableRenderer.render("fullFormGroup") call
message = "Copying...";
// initiates render. Note that this cannot be called from a thread which is already part of an HTTP request
portableRenderer.render("fullFormGroup");
do {
progress = getProgress();
portableRenderer.render("fullFormGroup"); // render the updated progress
Thread.sleep(5000); // sleep for a while until it's time to poll again
} while (copyExecuting);
progress = getProgress();
message = "Finished!";
portableRenderer.render("fullFormGroup"); // push a render one last time
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
});
statusThread.start();
// create a thread which initiates script and triggers the termination of statusThread
Thread copyThread = new Thread(new Runnable() {
public void run() {
File someBigFile = new File("/tmp/foobar/large_file.tar.gz");
scriptResult = copyFile(someBigFile); // this will take a long time, which is why we spawn a new thread
copyExecuting = false; // this will caue the statusThread's do..while loop to terminate
}
});
copyThread.start();
}
I suggest looking at our Showcase Demo:
http://icefaces-showcase.icesoft.org/showcase.jsf?grp=aceMenu&exp=progressBarBean
Under the list of Progress Bar examples is one called Push. It uses Ajax Push (a feature provided with ICEfaces) to do what I think you want.
There is also a tutorial on this page called Easy Ajax Push that walks you through a simple example of using Ajax Push.
http://www.icesoft.org/community/tutorials-samples.jsf

Resources