can i correctly finish an android app in Kotlin, when i swipe it out? - android-studio

I hope, I can formulate my question correctly and understandable.
When I write an Android App in Kotlin, I normally have a button to close the app and for example finish it with writing a file or something like that.
Now, sometimes I don't finish it with the button, but swipe it out. Then, the file is not wirtten..
Is there a Kotlin statement to catch the "swipe out" and perform some code? When I Inflate another view, at the end I have a dismiss-statement or dismiss.listener and can do some code.
example:
dialog.dismiss() or popupwindow.dismiss()
So question: is there a dismiss.app or something like that?

When your app's Activity is destroyed (either by the user swiping it away, or the system killing the app to free up some resources) it goes through the usual lifecycle steps, ending with onDestroy.
These steps also get pushed to any lifecycle-aware components that are observing that activity's lifecycle, including Fragments (like a DialogFragment) - so that will also get an onDestroy() call. Fragments can be destroyed at other times too, but you can look at the activity's lifecycle to see what's going on there if you need to.
But really, as a general rule you want to save data in something like onStop(), when the activity/fragment is going to stop being visible, i.e. it's going into the background. That's a good time to make sure you've saved all your important data and state, because the user may not be coming back, and you can't be sure onDestroy will be neatly called (e.g. there could be a crash, or the phone might suddenly lose power).
Don't rely on persisting data with the onSaveInstanceState() callback though - that's intended for saving UI state, and if the user backs out of the app / swipes it away, that's counted as a fresh start for the next time they load the app, so onSaveInstanceState won't be called (since the UI state isn't being saved). Use onStop instead (or onPause if you like - have a look at those links for more info on what the difference is)

Related

Phaser3 Scenes transitions

I'm new to Phaser3 and before starting a crazy project, I want to know how I should start, switch between scenes. I saw that there are several functions, start, launch, switch, run, resume, pause, etc.
Example, lets say I want to have 2 scenes, a Menu and a Game. I boot on the Menu and I want to go to the Game scene and if I click on a button then come back to the Menu scene.
I've achieved this by calling the start function, but I noticed that the all, init, preload and create functions are called every time and therefore I'm loading all the images, setting all the listener over and over again.
This seems wrong, should I be using the launch or switch functions and pausing and resuming? But how do I hide the previous scene?
Thanks in advance.
This question might be a little too broad, but with Phaser 3 in mind, it still depends upon what purpose your menu serves.
I think most games have a main menu that will generally be called when the game first starts, and then won't be called again.
If this is an in-game menu, where settings can be changed or part of the game can be reset/restarted, then it might not make sense to redirect to a completely different scene.
With Phaser 3's support of multiple scenes - with Dev Log #119 and Dev Log #121 probably being the best current sources of information - another option would be to start a new scene within the current scene to handle this.
However, if this is really just UI, there's nothing to stop you from creating an overlay, instead of spawning an entire scene.
If you're concerned about performance I might think about whether the entire menu needs to be called, or if a simplified menu would work. Also, make sure that you're preloading assets before you're in the menu and main game.
I personally use Boot > Preloader > Splash Screen > Main Menu > Main Game scenes, where the Preloader loads the majority of the assets I'll need. This has the downside of a longer initial load, but the upside of minimal loading after this point.
Scene Transitions
How I handle these in my starter templates is to add the scenes to the Scene Manager when creating the scene. Then I transition by start to the first scene.
this.scene.add(Boot.Name, Boot);
this.scene.add(Preloader.Name, Preloader);
this.scene.add(SplashScreen.Name, SplashScreen);
this.scene.add(MainMenu.Name, MainMenu);
this.scene.start(Boot.Name);
Then I simply keep starting the next scenes as needed.
this.scene.start(Preloader.Name);
For another game that uses multiple scenes I ended up creating the following function (TypeScript) to handle this:
private sleepPreviousParallelScene(sceneToStart: string): Phaser.Scene {
if (this.uiSceneRunning !== sceneToStart) {
// Make sure that we properly handle the initial state, when no scene is set as running yet.
if (this.uiSceneRunning !== "") {
this.scene.get(this.uiSceneRunning).scene.sleep();
}
const newScene = this.scene.get(sceneToStart);
newScene.scene.start();
this.scene.bringToTop(sceneToStart);
this.uiSceneRunning = sceneToStart;
return newScene;
} else {
return this.scene.get(this.uiSceneRunning);
}
}
In the game I was using this for, I was trying to replicate a standard tab interface (like what's see in the Dev Logs above with the file folder-like interface).
Ok, here is the deal. In phaser 3, the start function actually SHUTS DOWN the previous scene as it starts the new one. This is why you see the init, preload ext every time. If however, you 'launch' your scenes instead, then they will not go through the whole shut down, restart sequence. You can move them to the top or bottom, set to receive input or not, etc. HOWEVER, BEWARE! As of phaser 3.16, sleep or pause of a scene does NOT shut down the update. As a result, if you launch a scene, then sleep it, it basically does nothing other than maybe set the flag, saying it's asleep even though it really isn't. So any update processing will continue in any launched scene. You can short circuit the update with a flag of some sort at the beginning, (that's what I've resorted to), but the other gotcha is the camera size. All the scenes must therefore have the same camera size or they will render (even if "sleeping") and mess up your display.
So, bottom line, it's going to be messy until sleep and pause actually work.

minimize and getting back the display

I want to minimize my app and after the timer end get it back.
I use code below.
To minimize application use following line of code:
Display.getDisplay (MIDLET_CLASS_NAME).setCurrent (null);
To get the screen back use the following:
Display.getDisplay (MIDLET_CLASS_NAME).setCurrent (myCanvas);
But when phone display is dismissed and going to clock mode my midlet display isn't shown until press any button.
any idea?
From your question it sounds that you expect setCurrent to somehow "force" device to immediately display your screen or maybe return only after screen gets visible.
This is not so, as clearly explained in the API documentation for Display.setCurrent:
Requests that a different Displayable object be made visible on the display. The change will typically not take effect immediately. It may be delayed so that it occurs between event delivery method calls, although it is not guaranteed to occur before the next event delivery method is called. The setCurrent method returns immediately, without waiting for the change to take place...
...if the application is in the background, passing a non-null reference to setCurrent may be interpreted by the application management software as a request that the application is requesting to be brought to the foreground... These are only requests, and there is no requirement that the application management software comply with these requests in a timely fashion if at all...
Consider redesigning your MIDlet to adjust to specified behavior.
If myCanvas is an instance of Canvas, one can use showNotify() events.
For a generic Displayable screen isShown() method checks if the it is actually visible on the display.
Sometimes it could even make sense to let user explicitly confirm return from background, like
display.setCurrent(new Alert("back to foreground", "dismiss to continue...",
null, AlertType.INFO), myCanvas);

Alerts or Popups in MvvmCross

Does MvvmCross support a cross platform solution for displaying alerts or popups?
Searching the code I found MvxDialogActivityView but it has been commented out. Will this remain the case for now?
If there is no direct support how would you suggest this is best done? (Perhaps the ViewModel would change a property and call FirePropertyChanged so that the View would be aware of it and show an alert.)
Edit 16:04 16th June 2012
What I am trying to do for this specific case is as follows:
On the page a button is clicked, which causes a method to run in the ViewModel which does an evaluation to determine which of two messages should be shown to the customer. The message would be shown as an alert or popup (either native, or preferably totally styled by me). The message would fade after (the click of the OK button, or preferably 3 seconds).
After the message has been dismissed a new page will be navigated too (depending on which of the two messages was shown).
How to handle this definitely depends on what the situation is - there's no single best rule (IMHO)
For a general error display pattern, there's one proposal at http://slodge.blogspot.co.uk/2012/05/one-pattern-for-error-handling-in.html
I've used similar patterns for showing application level notifications - e.g. for when a long running operation completes or when a chat message arrives or...
One interesting post about how to display message boxes was: http://awkwardcoder.blogspot.co.uk/2012/03/showing-message-box-from-viewmodel-in.html - I'm not sure I'd completely follow the end solution, but there are definitely some good points there about what not to do.
For your updated scenario, I would consider using a messenger (like TinyMessenger) or using normal C# events exposed by the ViewModel and consumed by its View
On the page a button is clicked, which causes a method to run in the ViewModel
I would implement this using an ICommand bound to the button Click/Tap/TouchDown
which does an evaluation to determine which of two messages should be shown to the customer.
I would definitely implement the logic within a Service
This would be called from the ViewModel - and the result/decision would probably cause some property or private field state change.
How does the View then decide to show a message? I can think of 3 options:
The View could just respond to a Property change (normal Mvvm INPC) - this would be my preference
The ViewModel could expose a normal C# event which it triggers...
The ViewModel could send a Message
This last option (Messenging) is probably the most flexible solution here - it decouples the View and ViewModel in case you later decide to change responsibilities. To implement messenging, either:
implement your own hub (like I do for errors in http://slodge.blogspot.co.uk/2012/05/one-pattern-for-error-handling-in.html)
or use a generic solution like TinyMessenger
The message would be shown as an alert or popup (either native, or preferably totally styled by me).
This is a View concern - so would be entirely controlled by the View project. I'd use controls like: UIAlert, Toast, ToastPrompt, etc - all of which can be styled
The message would fade after (the click of the OK button, or preferably 3 seconds). After the message has been dismissed...
I'd use some form of Code Behind (or maybe a Behaviour in WP7) in the View. This would detect the click/fade/disappear and would then invoke either an ICommand (my preference) or public method on the ViewModel
a new page will be navigated too
This navigation would be requested from the ViewModel
(depending on which of the two messages was shown).
This would be easy to track through the above flow... presumably the ViewModel already knows what to show.
So that's what I'd do...
it keeps the application flow logic inside the ViewModels (and lower)
it keeps the presentation inside the Views
...but I'm sure there are other options :)
One final note... the fade out and then navigate logic can really get "messed up" by Switching/Tombstoning on WP7 and Android - this may or may not matter for your particular scenario.

XPages sometimes refresh and lose content

I hope someone can help me solve a very serious problem we face at the moment with a business critical application losing data when a user works in it.
This happens randomly - I have never reproduced this but the users are in the system a lot more than me.
A document is created with a load of fields on it, and there are 2 rich text fields. We're using Domino 8.5.3 - there are no extension lib controls in use. The document has workflow built in, and all validation is done by a SSJS function called from the data query save event. There is an insane amount of logging to the sessionscope.log and also this is (now) captured for each user in a notes document so I can review what they are doing.
Sometimes, a user gets to a workflow step where they have to fill in a Rich Text field and make a choice in a dropdown field, then they submit the document with a workflow button. When the workflow button is pressed (does a Full Update) some client side JS runs first
// Process any autogenerated submit listeners
if( XSP._processListeners ){ // Not sure if this is valid in all versions of XPages
XSP._processListeners( XSP.querySubmitListeners, document.forms[0].id );
}
(I added this to try and prevent the RTF fields losing their values after reading a blog but so far it's not working)
then the Server-side event runs and calls view.save() to trigger QS code (for validation) and PS code to run the workflow agent on the server.
95% of the time, this works fine.
5% of the time however, the page refreshes all the changes made, both to the RFT field (CKEditor) and the dropdown field are reloaded as they were previously, with no content. It's like the save hasn't happened, and the Full Update button has decided to work like a page refresh instead of a submit.
Under normal circumstances, the log shows that when a workflow button is pressed, the QuerySave code starts and returns True. Then the ID of the workflow button pressed is logged (so I can see which ones are being used when I am reviewing problems), then the PostSave code starts and finally returns true.
When there is a problem, The QuerySave event runs, returns true if the validation has passed, or false if it's failed, and then it stops. The ID of the workflow button is also logged. But the code should continue by calling the PostSave function if the QuerySave returns true - it doesn't even log that it's starting the PostSave function.
And to make matters worse, after the failure to call the PostSave code, the next thing that is logged is the beforePageLoad event running and this apparently reloads the page, which hasn't got the recent edits on it, and so the users loses all the information they have typed!
This has to be the most annoying problem I've ever encountered with XPages as I can find no reason why a successful QuerySave (or even a failure because mandatory fields weren't filled in) would cause the page to refresh like this and lose the content. Please please can someone help point me in the right direction??
It sounds as if in the 5% use cases, the document open for > 30mins and the XSP session is timing out - the submit causes the component tree to be re-created, and the now empty page returned back to the user. Try increasing the time out for the application to see if the issue goes away.
I would design the flow slightly different. In JSF/XPages validation belongs into validators, not into a QuerySave event. Also I'd rather use a submit for the buttons, so you don't need to trigger a view.save() in code. This does not interfere with JSF's sequence of things - but that's style not necessarily source of your problem.... idea about that:
As Jeremy I would as a first stop suspect a timeout, then the next stop is a fatal issue in your QuerySave event, that derails the runtime (for whatever reason). You can try something like this:
var qsResult = false;
// your code goes here, no return statements
// please and if you are happy
qsResult = true;
return qsResult;
The pessimistic approach would eventually tell you if something is wrong. Also: if there is an abort and your querySave just returns, then you might run in this trap
function noReturn() {return; } //nothing comes back!
noReturn() == true; --> false
noReturn() == false; --> false
noReturn() != false; --> true!!!!
What you need to check: what is your performance setting: serialize to disk, keep in memory or keep latest in memory? It could be you running foul of the way JavaScript libraries work.
A SSJS library is loaded whenever it is needed. Variables inside are initialized. A library is unloaded when memory conditions require it and all related variables are discarded. so if you rely on any variable in a JS Function that sits inside a SSJS library between calls you might or might not get the value back, which could describe your error condition. Stuff you want to keep should go into a scope (viewScope seems right here).
To make it a little more trickier:
When you use closures and first class functions these functions have access to the variables from the parent function, unless the library had been unloaded. Also functions (you could park them in a scope too) don't serialize (open flaw) so you need to be careful when putting them into a scope.
If your stuff is really complex you might be better off with a backing bean.
Did that help?
To create a managed bean (or more) check Per's article. Your validator would sit in a application bean:
<faces-config>
<managed-bean>
<managed-bean-name>workflowvalidator</managed-bean-name>
<managed-bean-class>com.company.WfValidator</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
</managed-bean>
</faces-config>
Inside you would use a map for the error messages
public Map<String,String> getErrorMessages() {
if (this.errorStrings == null) { // errorStrings implements the MAP interface
this.loadErrorDefinitions(); //Private method, loads from Domino
}
return this.errorStrings;
}
then you can use EL in the Error message string of your validators:
workflowvalidator.errorMessage("some-id");
this allows XPages to pick the right one directly in EL, which is faster than SSJS. You could then go and implement your own custom Java validator that talks to that bean (this would allow you bypass SSJS here). Other than the example I wouldn't put the notes code in it, but talk to your WfValidator class. To do that you need to get a handle to it in Java:
private WfValidator getValidatorBean() {
FacesContext fc = FacesContext.getCurrentInstance();
return (WfValidator) fc.getApplication()
.getVariableResolver()
.resolveVariable(fc, "workflowvalidator");
}
Using the resolver you get access to the loaded bean. Hope that helps!
My experience is that this problem is due to keeping page in memory. Sometimes for some reason the page gets wiped out of memory. I'm seeing this when there is a lot of partial refreshes with rather complex backend Java processing. This processing somehow seems to take the space from memory that is used by the XPage.
The problem might have been fixed in later releases but I'm seeing it at least in 8.5.2.
In your case I would figure out some other workaround for the CKEditor bug and use "Keep pages on disk" option. Or if you can upgrade to 9.0.1 it might fix both problems.

Blackberry application hangs and freezes on UI modification

I've written a Blackberry appliation with the Blackberry JDE, running on a 9000 simulator. I tested it a week or so ago and loaded it on a Blackberry 9000 phone, and everything worked just fine. Sometime between then and now, though, something went wrong.
My code does the whole moving arrow "loading things from the internet" or whatever thing, but no screens pop up. My original screen, which is just a MainScreen with a RichTextField doesn't load at all. This screen, at least, has most likely not changed in the passing week, so if something broke, it would be in one of the later screens/lines of code that it shouldn't even be getting to yet!
Is it possible that my .jad or .cod file are corrupted somehow? I noticed that when I first put code on my machine, I just stuck in the .cod file that Eclipse provided me. Then, last week, the .cod file it gave me didn't work, because it was ACTUALLY a zip file with a two .cod files inside of it. Using the .cod file with the same name as the .cod file they were in succesfully loaded my app. I did the same this time, and I don't get invalid cod file errors or anything, but the app is still as broken.
Is there some direction I should be looking? Is the issue likely to be in my code, the cod file, the phone, or somewhere completely else?
-Jenny
Edit: I've narrowed it down to the problem only occuring if I attempt to load a particular screen. My problem is that this screen is nearly identical to another screen that IS working just fine on the actual device. Both screens are generated from the same method (which makes a webservice call and gets XML back and parses it to populate the fields of the screen). The only difference is that the screen that is breaking is going to a different URL. This URL DOES work (both from a browser and from the simulated device), so I"m at a loss. The application doesn't seem to crash, (it's still running in the background), it just doesn't attempt to display anymore.
Edit:
Okay, I'm seeing some tunneling errors immediately after I load my app, (but before I execute any of my networking code). When i do execute my networking code, it works just fine, unless it happens to be for my "Rental" section. I commented out all calls to that, and made my menu item for Rentals simply make a print statement. The code behaves identically (it freezes, or displays a white screen after selecting the button). All other menu items work (including those that call threads or network methods). And the rentals menu sucessfully executes in the simulator.
private MenuItem _rentals = new MenuItem("My Rentals", 110,
10) {
public void run() {
//if the last thing I did was a rental
//just show the screen
//else, reload rentals
System.out.println("Rentals was selected");
displayError("Rentals was pressed");
// if(rental){
// System.out.println("It's a rental!");
// popScreen(getActiveScreen());
// pushScreen(_offeringsScreen);
// }else{
// System.out.println("Getting Rentals from scratch");
// RentalsThread _rThread = new RentalsThread();
// _rThread.start();
// }
}};
I'm at a complete loss here: The device debugger doesn't seem to even register me selecting the menu item, and not a single line of code executes! It just freezes! I'll try putting back in my RentalsThread call in the start of my program (which was also freezing) just to see if I can tease apart the problem with the Rentals Thread (which makes the Rental Screen), and the problem with the Rentals menu item.
Okay, I think I have this figured out.
1.) My code was still behaving identically even after commenting out everything because I wasn't rebuilding the .COD files (they automatically rebuild if you try to run it in the simulator, but don't when you're generating a .ALX file, for some reason).
2.) The code I had for generating the Rental Screen was adding things to said screen. Apparently this is all well and good on the simulator, but on the real device it's required that you do all graphics manipulation (even for graphics not yet displayed) in an event thread (I used invokeAndWait).
So, now everything seems to be working just fine. There wasn't anything wrong with my networking (nor did I think there was, because my other networking screen works just fine). I still don't know why I get all those weird tunneling network things before I start, but it doesn't seem to affect anything yet.
See also:
BlackBerry UI Threading - The Very Basics
BlackBerry threading model
several suggestions:
if you have some background work with resources like file IO or networking, app just may stuck there... provide error handling and try to debug app from device!
code signing, check latest code update for API which require signing. But since there are no errors this is doubtful.
To debug on device, run Blackberry Device Manager, attach phone to usb, in eclipse select project, Context Menu -> Debug As -> Blackberry Device.
See A50 How to Debug and Optimize
UPDATE I see "Tunnel failed" exception, so it's like network connection problem...
See tunnel failed in blackberry bold. why?
How to Configure Full Internet Access On BlackBerry
UPDATE Support - Application stops responding when opening a connection

Resources