onDestroy for making data persistent and sync with the server - java

I have a little problem to detect when the application is finished. I need to do some actions onDestroy like save the parameters into the database and make a final connection to the server.
The problem is that if I put the code in onDestroy its is called when the orientation changes for example. Putting
android:configChanges="orientation|keyboardHidden"
in the manifest for that activity the landscape/portrait layouts don't swap. And adding
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
}
Changes the layouts but the buttons and labels do not get the onClickListeners and the text labels correctly. How can I solve that? Thanks

The problem is that your layout items aren't initialized again because you're initializing them in your onCreate() function, and then you're disrupting them with a new layout in onConfigurationChanged().
One option is to move the initialization to a new function that gets called from both onCreate() and onConfigurationChanged().
Another option is to use the android:onclick="" (and related) attributes in your layout.
The option I would choose is different though. I would allow Android to manage orientation (and to call onDestroy()) and in onDestroy() I would install an Alarm for, say, 10 seconds (which I imagine is plenty of time to have onCreate() called again). In onCreate() I would cancel the alarm. When the alarm fires, I would perform my save actions.

Declare buttons and labels as class variable.

setContentView recreates your view, so you must rebind your data. the best approach would be a function called both from onCreate() and onConfigurationChanged(), with layout creation and bindings.

If you don't want to anything to happen when orientation changes occur, than you should not re-setContentView(). Basically you are telling your app: "DO NOTHING WHEN ORIENTATION CHANGES". So, remove the setContentView inside the onConfigurationChanged() or test for which orientation currently is active and then load desired layout resources.
When orientation changes onDestroy() is called because the changes restart your entire activity.
Read more here:
http://developer.android.com/guide/practices/screens_support.html#qualifiers
http://developer.android.com/guide/topics/resources/providing-resources.html
Orientation testing:
Setting the background of an Activity

Could you do that stuff in overriden finish() of the activity?

Related

Where is the difference between onCreate and onStart if both are called upon Activity change anyway? What's the purpose?

I've searched through dozens of Stackoverflow posts and the android doc but just couldn't find the answer.
According to the accepted answer of this SF-post the onCreate method runs when the activity is first created. It also notes that in here views are supposed to be created and list data is being binded.
Then the onStart Method runs but here's the issue. Where's the difference? If you do everything inside of onCreate, switch activities, your app will still display the same data, regardless whether you put the app in the background or switched activities.
So if you declare views in onCreate, what do you do in onStart? initiliaze the views to their R.id.view ? Fetch data?
onResume I suppose is then used for listeners since it's the gas and brake according to this SF-posts accepted answer.
onCreate() is called when the activity is first created. onStart() is called whenever the activity becomes visible, which includes when it is first created (after onCreate()) and after it is coming back to the screen from being stopped (e.g., another activity took over the screen).
So:
Put code in onCreate() that needs to happen when the activity is created (and use onDestroy() to clean it up)
Put code in onStart() that needs to happen either when the activity is created or when the activity returns to the foreground (and use onStop() to clean it up)
Frequently, we do not do anything special when the activity returns to the foreground, in which case you do not need to worry about onStart() or onStop().

Progresscircle until activity did load

How can I show a progresscircle, until my whole activity did load? (Did load means, loading the activity and do some functions which need around 1-2 seconds)?
Kind Regards
You might want to look at this image to get an idea:
That's an Activity's lifecycle.
A nice way to do it would be to make the ProgressBar visible at the very start of onCreate() and make it invisible (or GONE) at the end of onResume(). Make sure you inflate the layout before accessing it though, or you'll run into errors.
(More information about Activities: Click here.)
Edit:
Maybe it's not a bad idea to use an AsyncTask for those long functions. Pass the ProgressBar to the task's constructor, then set the ProgressBar's visibility to VISIBLE in the onPreExecute function, and to GONE in the onPostExecute function.

Create new instance on launch

I'm fairly new to android, but I've noticed that pretty much every tutorial begins with this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
But I don't want the state to persist throughout relaunching the app. I want the user to start at the beginning if they relaunch the app. How can I achieve this?
In Android, state management is up to you during the Activity lifecycle. The onCreate, onPause, onDestroy and other lifecycle methods are all available to save and restore activity state and do other things. If you don't want your app to save any state, whether it be text boxes or animations or what not then don't capture it and restore it in these events.
Bundle savedInstanceState is only set by you when the activity is paused or stopped allowing you to store state and grab it in the onCreate or onResume methods, but that also happens on orientation change of the layout (the user tips from portrait to landscape) and then you probably do want to save state details in that Bundle.
And of course you could always reset any fields overriding onResume.
Also, the Activity Launch Modes might be worth looking at. A lot of times I will set my main activity to singleTop to have only one instance launched at any given time.
protected void onPause()
{
finish();
}
It will kill the activity as it pauses.and it will create a new instance each time.

When I rotate my Android device, the XML changes back to main.xml

I'm writing an Android application. I have two important XML files - main.xml, and new.xml. Here is my Java Activity source code:
// package declarations, imports, etc
public class MainActivity extends Activity {
#Override
public void onCreate(savedInstanceState) {
super.onCreate(savedInstancestate);
setContentView(R.layout.main);
}
// as you can see, the content of the initial layout is found in main.xml
// I want to change the layout so it has the content of new.xml (when I press a button)
public void ButtonAction(View view) {
setContentView(R.layout.new);
}
}
So it goes like this: in my main.xml file, there is a button. As dictated in the main.xml file, when I press that button, it calls the method ButtonAction. When the button is pressed and ButtonAction is called, I want to change the content of the layout to be the contents of new.xml.
The above code works, but only kind of - it's not permanent. When I rotate my device, it appears to refresh the activity with the contents of main.xml. So I can get it to do what I want, but when I rotate the device and view it in a Landscape layout instead of the typical Portrait layout, it reverts.
How do I fix this?
When you rotate the screen the entire Activity is destroyed and started from scratch, including calling onCreate() with setContentView(R.layout.main);. You should store the last layout chosen in a variable and load this variable instead with:
setContentView(lastLayout);
You need to override onSaveInstanceState() and onRestoreInstanceState() to remember the layout choice while the app is running. This approach is only temporary since this state is lost when the app is closed.
Otherwise you can use SharedPreferences (or something similar like a database or generic file) to remember the layout choice across multiple sessions.
Use onSaveInstanceState() to save the state of your activity and use onRestoreInstanceState() to retrieve the state your activity.
onRestoreInstanceState() is called after onStart(), whereas onCreate() is called before onStart().
onRestoreInstanceState() is called only when recreating activity after it was killed by the OS.
Use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
icicle.putLong("param", value);
}
Here is a tutorial
http://www.androidcompetencycenter.com/tag/onrestoreinstancestate/
Just to clarify, if you are in landscape or portrait Android looks for the layout file in either the -land directory first, if it's not found then it checks the default layout directory. Your files should be named as follows, and will be loaded by the system depending at runtime on the device's current configuration:
res/layout/main.xml
res/layout-land/main.xml
Check the documentation on Providing Resources for more information.

Why is it that when I swap to landscape, my changes to the User Interface are undone?

I have another question!
I have a configure Activity in my app. On it, I have a ListView. Now adding & removing items to & from it works, but when I rotate the screen to landscape or back, all added & non-saved items in the ListView get removed... I wonder why this is... Why is this?
When screen orientation changes, by default, the activity will be destroyed and create again. That means, the onCreate will be called again once the orientation changed. There are basically two way to solve your problem:
Save your activity state before destory and load it back when create
Set the Activity in AndroidManifest that not to handle screen orientation change.
E.g.
<activity name="..."
android:configChanges="orientation" .../>
When you rotate the handset, the onStart method of you Activity is invoked. Check maybe you do some sort of initialization there.
I've solved it partially. Now it is able to hold on to the changes when changing to landscape view, but not the other way back to the normal view. I did it through the use of protected void onSaveInstanceState(Bundle saveState). But as I said, this doesn't work when it changes back from Landscape... Anybody got any ideas about this?

Categories