Download data and support screen rotation - android

I am trying to make an app that is downloading some data from the web and display it on a list. I am using AsyncTask but when I rotate the phone I don't get the results.
I want to ask what is the best way to download data and handle orientation changes? I also want to display a progress dialog so the user can see the complete percentage.
Thank you

what you can do is you can set the orientation in only one form so by this your activity is not recreated or you can add this line in your manifest that will handle orientation change
<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>
or you can save the state of you application in restore it when orientation is changed
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putInt("param", valueInt); // you can save values that you want to
//retain when you orientation change is done
}
and onCreate method you can get them and assign them torelevent views
public void onCreate(Bundle bundle) {
if (bundle != null){
valueInt = bundle.getLong("param");
}
}

Related

Device Orientation Destroy Activity

I've got my app working for the most part, but I've got buttons and text views with text that change based on some state variables. When I change the device's orientation it destroys and recreates the activity in the new orientation. I've tried adding
android:configChanges="orientation"
to the manifest file. I've also tried overriding the onConfigurationChanges method to "do nothing" but the text still reverts to default.
I know I can lock the user in to one orientation, but I would rather have the app usable in either orientation.
Alternatively, is there a way to determine which orientation the user opened the app in and lock them in that orientation until they restart the app?
Edit:
Thank you Kabir,
android:configChanges="orientation|screenSize"
works perfectly
For API 12 and below:
android:configChanges="orientation"
if you are targeting API 13 or above
android:configChanges="orientation|screenSize"
Actually orientation changing works by destroying and recreating an activity. Some views are able to save theirs states, others no. TextView doesn't save its state (in this case text) as it tends to show static text. If you want to save TextView's state during the configuration changes, you can do as following:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
/*
1st argument is key, 2nd is value to save
*/
outState.putString("savedText", myTextView.getText().toString());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
/*
The argument is key to get saved string
*/
myTextView.setText(savedInstanceState.getString("savedText"));
}
These onSaveInstanceState() and onRestoreInstanceState() are Activiy's methods.

Android save state on orientation change

I've got an Android application which maintains state regarding distance traveled, time elapsed, etc. This state I can conveniently store in an object and store a reference to that object in the Bundle when Android calls onDestroy() when the user changes the screen orientation, then restore the state in onCreate(Bundle savedBundle). However, I also have some state in the Buttons and EditText objects on the screen that I want to persist through screen orientations. For example, in onStart(Bundle savedBundle) I call:
_timerButton.setBackgroundColor(Color.GREEN);
_pauseButton.setBackgroundColor(Color.YELLOW);
_pauseButton.setEnabled(false);
Then throughout the operation of my app, the colors/enabled status of these buttons will be changed. Is there a more convenient way to persist the state of user interface items (EditText, Button objects, etc) without having to manually save/restore each attribute for each button? It feels really clumsy to have to manually manage this type of state in between screen orientations.
Thanks for any help.
Add android:configChanges in the Manifest file
<activity name= ".MainActivity"
android:configChanges="orientation|screenSize"/>
By default, this does not work because changing the orientation causes the onCreate method to be called again and redraws the view.
However, if this parameter is included, the framework will handle preserving the state of the screen or layout if the orientation is changed.
Refer following official documentation for more info:
Activity Lifecycle
Handling configuration changes
To save your variable or values you should use onSaveInstanceState(Bundle); and when orientation changes then should recover values should use onRestoreInstanceState() as well, but not very common. (onRestoreInstanceState() is called after onStart(), whereas onCreate() is called before onStart().
Use the put methods to store values in onSaveInstanceState()
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
icicle.putLong("param", value);
}
And restore the values in onCreate():
public void onCreate(Bundle icicle) {
if (icicle != null){
value = icicle.getLong("param");
}
}

onCreate called whenever I the screen autorotates

In my app, I use the onCreate() method to initialize various variables. However, whenever I rotate the device, and the screen auto-rotates, onCreate() is called again, which re-initialize my variables. Is that how it's supposed to work? Where should I put code that I only want to be run once, when I start the app?
The above answers will lock your Activity into a specific orientation, which is generally not proper behavior for an Android app.
What you should be doing is storing your activity's state so when it gets recreated you can repopulate the UI with the stored values.
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
// put your values in the Bundle
outState.putString("TextView1Text", textView1.getText()); // for example;
}
Then in your onCreate() method you can restore the values
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
textView.setText(savedInstanceState.getString("TextView1Text"));
}
}
This will also work when the user leaves the app via the home button or other means.
In the manifest put this line in all the activities that you want PORTRAIT
android:screenOrientation="portrait"

Values changing when app turns from portrait mode to landscape mode in android

I am working on android apps. My app should work both in portrait and landscape mode. I adjusted all the layouts by keeping all layout files in layout-lan folder. But now my issue is with functionality i.e when the app is changed to landscape mode the values of my parameters are changing and due to this I am getting crashes. i.e i kept a counter value but it is displaying wrong count value when turned to port-lan. Also the functionality is changing due to this.
Please help me in this regard.
Each time you rotate the devide, onCreate method is being called again. You can save the values by overriding onSavedInstanceState and get them back in onRestoreInstanceState or in onCreate method. For example:
save the value:
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean("booleanValue", true);
}
restore the value (you can call this in onCreate as well):
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null && savedInstanceState.containsKey("booleanValue")) {
boolean myBoolean = savedInstanceState.getBoolean("booleanValue");
}
super.onRestoreInstanceState(savedInstanceState);
}
Your activity restarts every time the orientation changes.
You have to store your values in onSaveInstanceState and restore them in onRestoreInstanceState. You will find the details here: http://developer.android.com/guide/topics/resources/runtime-changes.html
those values change because the activity gets destroyed and re-built during rotation,
please check the developers guide on how to save your activity state.
http://developer.android.com/training/basics/activity-lifecycle/recreating.html#SaveState

how to retain the state of activity in android

How do I retain the state of an activity in android? I have two layouts for portrait and landscape in layout and layout-land. I am loading the value from service at the time I am showing progress dialog. If loaded user rotates the device to landscape at the time also loading. How do I avoid that? user typed content in webview that also refreshed. How do I avoid that, can anybody provide an example?
Thanks
When orientation changes, the Activity is reloaded by default. If you do not want this behavior then add this to the Activity definition in your manifest:
android:configChanges="orientation|keyboardHidden"
For more detail, see Handling Runtime Changes
You can use the onRetainNonConfigurationChange() callback to store arbitrary data. It is called just before your application is about to be recreated.
Then, in onCreate() just check if some data were put aside by calling getLastNonConfigurationInstance() that returns the Object you put aside or null.
See this article on android developers.
Here's a sample borrowed from the link above:
#Override
public Object onRetainNonConfigurationInstance() {
//this is called by the framework when needed
//Just return what you want to save here.
return MyBigObjectThatContainsEverythingIWantToSave;
}
Automagic restore of previously saved state:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MyDataObject MyBigObjectThatContainsEverythingIWantToSave = (MyDataObject) getLastNonConfigurationInstance();
if (MyBigObjectThatContainsEverythingIWantToSave == null) {
//No saved state
MyBigObjectThatContainsEverythingIWantToSave = loadMyData();
} else {
//State was restored, no need to download again.
}
...
}
When orientation changes, the Activity is reloaded by default. If you do not want this behavior then add this to the Activity definition in your android manifest file :
android:configChanges="orientation|screenSize|keyboardHidden"

Categories

Resources