Stopping onCreate being executed on screen rotation in Android - android

I have an activity with 4 elements. A spinner containing a list of dates, a spinner containing a list of hours, a button and a list view. The spinner's selected items are used to form a web service URL which is called when the button is clicked and the response is shown in the list view.
The issue is if the user views the app in portrait mode, chooses a date, chooses an hour and clicks the button, the response of the web service call is shown in the list view however, if the device is rotated to landscape then the data in the list view is gone (because in order to get it there a button click is needed).
I understand that onCreate is called when the screen is rotated. I do not want to force the orientation so is there any way I can stop the list view being cleared? Note that the selected values in my spinners remain the same after rotation, it is just the response in the list view that is lost.

Simplest way to prevent activity recreation put this in you AndroidManifest
<activity android:name=".YourActivityName"
android:configChanges="orientation|keyboardHidden|screenSize">
Read this for more info - Supporting Multiple Screens

You can force activity screen orientation in AndroidManifest.xml by setting screenOrientation property:
<activity android:name=".FooActivity"
android:screenOrientation="portrait"/>
This is a half-solution. If you want to handle screen rotation, you should save and restore activity state. This is the major, royal PITA in any Android application I've seen.
The problem is, that your application logic is mixed with view code, which can be destroyed at any moment. Perfect combination, Google! It's like running a function that can disappear during execution. :)
To counter this sorry design decision you may want to move your application logic to service, which will not be destroyed when screen rotates. This 2-layer design is closer to universally accepted MVC pattern, as you separate your logic from your view. Service stays, activity attaches and detaches from service on demand, making screen rotation handling a breeze.
If you're dealing with webservices, do not try to invent your own solution for this. There is couple of nice libraries to handle this nicely, such as RoboSpice and you'll probably never come with any quick solution that is as good as those libs. Give it a try.
Also, watch this Google I/O video about developing Android REST client applications: https://www.youtube.com/watch?v=xHXn3Kg2IQE

Have your button set a static class variable, or shared preference. Then, call a method that reads that value, and does what you want. THEN, put a call to that same method, in onResume(), possibly based on a condition... I think that's what's worked for me. When you come back from configuration change or kill, onResume() should re-do whatever you had last done.

Related

Android - Manipulating view position during onRestoreInstanceState

I have made a simple dice game that makes use of the setTranslationY() method to indicate if a dice should be ignored for the next dice roll. This all works fine, except that when I try to restore the state of the app after a screen rotation, my restoring method cannot seem to use setTranslationY() on the views that need it.
I have confirmed time and time again the the method IS being called for all views that should be nudged upwards a little bit, but the views stay where they are.
If it is so that the app needs to go through the process of completing onCreate(), onStart(), onRestoreInstanceState() and onResume() before being able to manipulate views then please advise on how to achieve this. I need this to happen consistently upon every device rotation.
You can retain the state of your application by informing Android you'd like to handle the logic for screen orientation yourself, rather than allowing the OS to trash and rebuild the entire Activity whenever the user tilts the screen. You can do this by adding the android:configChanges attribute to the Activity entry in your AndroidManifest.xml:
<activity android:name=".YourActivity"
android:configChanges="orientation"
android:label="#string/app_name">
This should hopefully preserve the state of your animated Views.

What is the advantage of letting an activity be destroyed on rotation?

I have used both approaches:
Let the activity be destroyed on rotation
Don't let the activity be destroyed on rotation
My approach almost everytime is to catch the rotation event and if needed call the setContentView and add some components again. If not, just let it rotate and the layouts are designed to adapt.
So far I only have seen advantages on letting it be destroyed on screens with very complex construction that are very dynamic, and whenever I rotate and not destroy show some flickering when re-building the screen.
The overhead of having to pass the state with onSaveInstance, onRestoreInstace is sometimes very error prone, and somehow time consuming.
Am I missing something?
UPDATE:
I'm not doing any kind of if "Orientation.XPTO == ..." on my code. This is the logic of each of the 2 approaches (the code is reused):
When destroying
onCreate -> DrawUI() setContentView and add views -> fill() add content
When not destroyed:
onCreate -> DrawUI() setContentView and add views -> fill() add content
onRotation -> DrawUI() setContentView and add views -> fill() add content
When calling setContentView after rotation it will pick the right layout for the device orientation (Check this answer by Google's Reto Meier https://stackoverflow.com/a/456918/327011 )
And the DrawUI and fill would have to have the logic for both the portrait and landscape layouts as the activity can be created on each of the two orientations to begin with.
Am I missing something?
Yes. You are assuming that your alternative is somehow less error prone.
By not going through the destroy-and-recreate cycle, you have to ensure that you are handling changing every resource for every possible configuration change.
Don't let the activity be destroyed on rotation
Unless you are using android:screenOrientation to force your activity into a single orientation (e.g., landscape), you cannot only handle rotation-related configuration changes. You need to handle all configuration changes. Otherwise, as soon as the user drops their device into a dock, removes it from a dock, changes language from Settings, attaches or detaches a keyboard, changes the global font scaling, etc., your app will break.
This, in turn, means that on every configuration change, you need to:
update your UI for your potentially new string resources
adjust or reload your layouts (and by "adjust" that includes changing any drawables, animations, menus, etc.)
anything else tied to your resources (e.g., array lists in your PreferenceFragment)
The problem is that you are going to forget something. For example, you will miss changing a string associated with an action bar item, so now most of your UI is in Spanish and that action bar item is in English. The sorts of things you are going to forget will be less obvious (how often do you test your Spanish translation?).
Your activity is destroyed to give you the opportunity to reconfigure yourself for the new orientation.
From the developer.android.com:
When the screen changes orientation, the system destroys and recreates
the foreground activity because the screen configuration has changed
and your activity might need to load alternative resources (such as
the layout).
For example, in landscape mode you may require a completely different layout, or may want to load in graphics that would not appear stretched. The best way of doing this is allowing the activity to be created again, which will allow the linking to the layout file to change to a more orientation-friendly layout.
See http://developer.android.com/training/basics/activity-lifecycle/recreating.html for more info and how to deal with the orientation change
If you want to disable the recreation you can add
android:configChanges="orientation"
to your Activity element in AndroidManifest.xml. This way your Activity will not be reloaded.
onSaveInstance and onRestoreInstace should only be used for passing through session information, for example the current text in a TextField, and nothing generic that can just be loaded in again after onCreate.
If you, restarting the Activity, requires recovering large sets of data, re-establishing a network connection, or perform other intensive operations then using the onSaveInstanceState() could potentially cause your noted symptoms:
A poor user experience (i.e. "show some flickering")
Require consumption of a lot of memory
onSaveInstanceState() callbacks are not designed to carry large objects.
To retain an object during a runtime configuration change:
Override the onRetainNonConfigurationInstance() method to return the object you would like to retain.
When your activity is created again, call getLastNonConfigurationInstance() to recover your object.
However:
While you can return any object, you should never pass an object that is tied to the Activity, such as a Drawable, an Adapter, a View or any other object that's associated with a Context. If you do, it will leak all the views and resources of the original activity instance. (Leaking resources means that your application maintains a hold on them and they cannot be garbage-collected, so lots of memory can be lost.)
Source
Unless you are able to pass the Object(s) smoothly I personally think it is more advantageous to handle the configuration change yourself, meaning not to destroy.
If you have a target API of 13 or higher: You must include screenSize in your configChanges. Starting with API 13 the screen size also changes on orientation change and you'll need to account for this. Prior to 13 your Activity would handle this itself.
android:configChanges="orientation|screenSize"
Some time it is useful when you are using different layouts for (Landscape / Portrait ). and using different type of views for example ListView in portrait and GridView in landscape.
I guess you are not considering the standard way of creating the android layouts. Please correct me If I'm wrong. Are you using two res folders with -port,-land separately to tell android system to choose in runtime to load the different assets and layout on the basis of orientation.
This example can give you a clue to manage layouts in different orientations.
Here is the android stanard document. Please check with "land" and "port".
Hope this will help you.

Why not use always android:configChanges="keyboardHidden|orientation"?

I was wondering why not use android:configChanges="keyboardHidden|orientation" in every (almost every ;)) activity?
Goods:
no need to worry about your activity been rotated
it's faster
Not so nice:
need to change your layouts if they are depending on screen size (e.g. layouts with two columns or so)
Bad:
no flexible way to have different layouts on different orientation
not so good when using fragments
But if we don't use different layouts, why not?
Quick Background
By default, when certain key configuration changes happen on Android (a common example is an orientation change), Android fully restarts the running Activity to help it adjust to such changes.
When you define android:configChanges="keyboardHidden|orientation" in your AndroidManifest, you are telling Android: "Please don't do the default reset when the keyboard is pulled out, or the phone is rotated; I want to handle this myself. Yes, I know what I'm doing"
Is this a good thing? We shall soon see...
No worries?
One of the pros you start with is that there is:
no need to worry about your activity been rotated
In many cases, people mistakenly believe that when they have an error that is being generated by an orientation change ("rotation"), they can simply fix it by putting in android:configChanges="keyboardHidden|orientation".
However, android:configChanges="keyboardHidden|orientation" is nothing more than a bandaid. In truth, there are many ways a configuration change can be triggered. For example, if the user selects a new language (i.e. the locale has changed), your activity will be restarted in the same way it does by an orientation change. If you want you can view a list of all the different types of config changes.
Edit: More importantly, though, as hackbod points out in the comments, your activity will also be restarted when your app is in the background and Android decides to free up some memory by killing it. When the user comes back to your app, Android will attempt to restart the activity in the same way it does if there was some other configuration change. If you can't handle that - the user will not be happy...
In other words, using android:configChanges="keyboardHidden|orientation" is not a solution for your "worries." The right way is to code your activities so that they are happy with any restart Android throws at them. This is a good practice that will help you down the road, so get used to it.
So when should I use it?
As you mentioned there is a distinct advantage. Overwriting the default configuration change for a rotation by handling it yourself will speed things up. However, this speed does come with a price of convenience.
To put it simply, if you use the same layout for both portrait and landscape you're in good shape by doing the overwrite. Instead of a full-blown reload of the activity, the views will simply shift around to fill the remaining space.
However, if for some reason you use a different layout when the device is in landscape, the fact that Android reloads your Activity is good because it will then load up the correct layout. [If you use the override on such an Activity, and want to do some magical re-layout at runtime... well, good luck - it's far from simple]
Quick Summary
By all means, if android:configChanges="keyboardHidden|orientation" is right for you, then use it. But PLEASE be sure to test what happens when something changes, because an orientation change is not the only way a full Activity restart can be triggered.
From my point of view: If the layout is the same in both landscape and portrait mode - you might aswell disable one of the two in your app.
The reason why I state this is that I as a user expect the app to provide me with some benefit, when I change orientation. If it doesn't matter how I hold my phone, then I don't need the choice.
Take for instance an app where you have a ListView, and upon clicking a ListItem you want to be shown a detailed view for that item. In landscape you would od this by dividing the screen in two, having the ListView on the left and the detailed view on the right. In Portrait you would have the list in one screen and then change the screen to the detailed view when a ListItem is selected. In that case orientation change makes sense as well as different layouts.
I don see why.... occasional restarts are ok in my opinion... configChanges handles most cases for me... well maybe in some types of applications this can be problem but it depends really on type of app and how you restore state when app restarts... When one of my app restarts user is logged back and last activity opens by my code and user jus loses some steps to go back where he was but not big deal.. In other some state is always persisted and some state is always restored on restart. When activity restarted it had to be that app have not been used or something... so no problem at all... In game for example this can be problem maybe or in some other type of app I don't know...
I say that when you do it this way applications just works fine under normal circumstances. And code is much more readable without ton of logic needed for saving and restoring where u just can make new bugs and have to maintain it all the time... sure if android gets out of power and kill you application window it lose the context and starts again, but this happen just in special situations and on newer devices I belive this is more and more rare...
So kill me, but I use this across applications quite successfully...
android:configChanges="locale|keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
But I understand that for some special kind of applications it may be not good way but most of apps can live with this just OK.
Yeah I think pausing will make it quicker than releasing the player. Still have the pause though.
Have now found a solution that won't pause the song.
State in the manifest that you will handle the config change for screen orientation and then use the onConfigurationChanged method to load the layout file. By doing this in logCat I can see onPause, onCreate & onResume aren't called, and therefore the song isn't paused.
update the manifest to handle the orientation.
android:configChanges="orientation|screenSize"
add this code
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_main);
}

Activities, Views and Dialogs in Android. Proper application structure for game

I was in the midsts of tinkering in android with the goal of trying to make this small exploration game. I actually got pretty far so far: a nice sprite system, a title screen with a main menu that is all in game code (no UI buttons or anything) that launch various activities. An activity that loads this cool map view, that when clicked on will load up another view of a more detailed "zoomed in" action part of a map. It all works pretty well but now I am left wondering how well I am going about this.
(What happens to a view when you instantiate and then move the set the context to a new view? I am guessing as long as the activity is alive all the instantiations of various views that an activity uses are still good? And in an activities onPause is when id have to save the data thats changed in these views to persist the state in the event the user quits the game etc.. ?)
I have three menu options at the start of the game. The main one is:
New Game
The new game, I launch my main map
activity that can launch three views:
First two are a loading screen for
the second, a map screen.
Third view is a more detailed action
orientated part that uses this sprite
engine I developed.
It all works pretty good as in the map view you click on a cell it tells the Calling Activity through a listener to start the detailed action view, and passes in the ID of the cell (so it knows what objects to load in the detailed view based on the cell clicked in second view). (This took me awhile to figure out but someone helped here on another question to get this.) Reference that helped me on this part here. I also used the various information here on ViewSwitcher.
I got even a yes no dialog box in the second view that asks if they really wanna goto that cell when they click on it, a yes tells the calling activity to set the new view. What helped me to get this working was this reference here. I also had to fiddle with the calls to getContext and that, I am still not 100% sure what getResources and getContext do for me.
So is it bad practice to call and load a dialog from a view? If it is, then I don't understand how if I have an event in the view that needs to pop up a dialog how I do that? Call back to the activity and let the activity handle it the dialog response and then call a method on the view for the response?
So far all this works great, I did have a bit to learn about threads too. I spawn a different thread for my MenuView (handles the detection of button clicks and responses), my CellMap view which handles the cool big map that users can click on to see the indepth view which is my SystemView view.
So basically the activity call list is like this:
Home.Activity -> ScrollMap.activity which listens to CellMap wher ethe Yes/No dialog apperas (in the view of CellMap) and if the answer is yes to the question, then the onTouchEvent starts up the SystemView view using
private CellMap.MapClickedListener onTouchEvent=
new CellMap.MapClickedListener() {
#Override
public void onMapClick(int id) {
setContentView(new SolarSystem(theContext,id));
}
};
To help anyone else, that listener had to be defined in my CellMap class. Then in the ScrollMap activity when I am about to start the CellMap I just call a method to CellMap sets the map click listener. So far this is the only way I have been able to get data from a dialog (in this case a it was clicked so set the new view) back to the calling activity. Is this proper practice?
Now my biggest question is, I have a playerObject class I want to initialize on new game event (I know how to detect that push) and that then is available to any view in any activity for the life time of the cycle. So far the game activity has just two (3 if you count the loading progress bar) views. I want to get the players name, is that another activity or view? I cannot find a decent tutorial of just how to make a simple input dialogg box that would return a string.
How do i go about passing this stuff around? After I get the players name from wherever that edit box is to be loaded, I want to set the players name in the class and pass that class instance off to another view or activity so they may get at that data. Everything I have searched on this seemed like overkill or not the right way. Whats the best way to pass this "playerClass" around so that I can access it from other views (to say display the players name in every view).
I also have my Home Activity that waits for an onClick on 3 buttons, it then launches their activity that shows the view. I realize a continue game and new game are the same activity and will just change in data loaded off the drive to restore a save game. When the new game button is clicked I would love to get the players name they want to use and of course set the member of the playerClass to this name so it persists.
Where do I call (an edit dialog is it?) the edit dialog from? (more over how do I build one that can take an okay button and input from keyboard etc). Id also like to make it pretty, maybe I could have a simple view that has one edit box in it and a nice image background (though I haven't figured out how to place the edit boxes to fit nicely matching a background i draw for it. I guess id like an edit dialog I can skin to look how i want it to and fit the look of the game).
I am actually kinda happy what I got so far its looking not to bad, just not sure about some specifics like getting user input for a name of the player. Storing that information and passing it then to other activities and views.
Is it better to have one GameMain activity, and a ton of views:
Map view
Character sheet view
inventory view etc etc?
Or Should there be diff activities in there somewhere as well?
You've written a lot here, so I'm go gonna go ahead and answer the questions I think you're asking.
First, how can one share information between activities and views? If you're just sharing it between views in a single activity, store it in the instance of the Activity subclass.
Sharing between activities requires a little bit more. Instead of using an instance of the default Application class, you can create a subclass of Application and use that instead. Put your data in fields of that subclass. To tell your app to use your subclass, modify the app manifest like so:
<application
....
android:name=".YourAppClassNameHere">
....
</application>
As for getting user input, the simple answer is use the built-in EditText view. since you seem to want to give your game a more "custom" style, though, you may need to go about creating your own editable textbox. That and buttons should allow for most sorts of basic user input.
Now, good practice vis-a-vis activities and views. I'm not aware of a standard for this, but when designing I generally try to think of activities as more conceptually separate elements, whereas views are conceptually interwoven. the line between the two is dependent, in part, on the scope of the app; an app with a narrow focus can afford to break more actions down into different activities than can one with a much broader focus.
Your "GameMain" example is a bit on the fence, but I think you've made the right choice: the activity is "playing the game," as opposed to a menu or high-scores table, and the views present different aspects of the game being played.

How can I keep current screen (contentView) when l Iaunch a new Activity

I have an NoContentViewActivity which has no Content View (i.e. I did not call setContentView() in the onCreate of my Activity).
My question is how can I keep the content view of the launching activity on the screen? Right now, I am getting a blank screen whenever I launch NoContentViewActivity? I want the content view of the launching activity (the activity which start the NoContentViewActivity) to show on the screen.
Thank you for any help.
Excuse me, people, but my guess is that hap497 wants exactly the thing he wants. There is a bunch of situations where invisible activity would fit while Service will not.
Imaging you want to show a set of dialogs, each next of them is shown after the previous one based on the user choices. And imaging you want to have this (exactly the same) functionality to be available when pressing different buttons on different (lots of them) activities.
To write the same dialog processing logic would be an overkill whether the transparent activity will deal nicely...
Anyway, as stated above, all you need to do is to specify:
android:theme="#android:style/Theme.Translucent"
or
android:theme="#android:style/Theme.Translucent.NoTitleBar"
(if you do not want a titlebar either)
It sounds like you'd be better off using a Service than an Activity. Activities are for code that is to be viewed; Services are for code that runs without a UI, which is what it sounds like you want.
An Activity with no Views assigned is an empty black screen, so it will still obscure the calling Activity. You could make your Activity transparent by assigning it a transparent theme:
android:theme="#style/Theme.Translucent"
Keep in mind though, that your invisible Activity will have focus, so the user won't be able to interact with the Activity underneath.
Why do you want to create a fully transparent Activity? As Daniel suggests, a Service might be a better solution to your problem if you genuinely don't want any user interaction.

Categories

Resources