I'm making a manga application but I stuck with save current scroll position when user rotate their device (landscape to portrait or portrait to landscape). I'm using RecyclerView and GridLayoutManager. Here is two block code that I have researched on the internet:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
rvItems.getLayoutManager().scrollToPosition(savedInstanceState.getInt("position"));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("position", ((GridLayoutManager)rvItems.getLayoutManager()).findFirstCompletelyVisibleItemPosition());
super.onSaveInstanceState(outState);
}
I'm using it and either in onResume() or onPause(), none of them are working. So I'm asking for any idea or suggestion that solve my problem? Any comment will be approriate.
P/S: One more problems, Is there any solution for stop loading all resource/data in current activity while user rotates their screen? I mean in my application, there might be numerous data and resource either text and images, as I know, every time user rotate their screen, the function onCreate() and onDestroy() was called which every data in onCreate() function will be loaded again. I need the resource/data only load one time since it's opened, then it won't load resource when user rotates their screen.
My writing might be very bad but now I'm sticking with many problems without any solution I can think or search in internet.
Thanks for reading!
add this to your activity tag in manifest
android:configChanges="orientation"
Related
I'm writing my first Android app. Essentially it shows and controls the score of a straight pool match. I've read articles about the lifecycle of an activity but I still have a problem I don't understand:
When I switch back to my app with a running game (so a score different from the initial 0:0 is shown) the activity sometimes loses its state and shows 0:0 instead of the score when I left the app. I overloaded the methods onSaveInstanceState and onRestoreInstanceState. The former get's called when I press the home button of my device. The latter never gets called. I've read that the method only gets called when onCreate is called. The onCreate method doesn't get called although the app needs longer than usual to reload after switching to some other apps in between. So I think the activity does get rebuild but obviously not by onCreate and the saved score is not loaded by onRestoreInstanceState.
Can you explain me what's happening and how to achieve the desired behaviour? Thank you very much!
edit: I was asked to post my onCreate() and onSaveInstanceState() methods. I tried to shorten them in a useful way. Please tell me If there is anything unclear or missing.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GameSetting gameSetting = getGameSettings();
final GameData gameData = new GameData(gameSetting.getLeague());
game = new GameLogic(gameData);
scoreViews.put(PlayerId.PLAYER_A, (TextView) findViewById(R.id.playerAScore));
}
#Override
protected void onSaveInstanceState(#NonNull final Bundle outState) {
GameDataInstanceSupplier.saveInstance(game.getGameData(), outState);
// inside the method the data gets saved like
// outState.putInt(STATE_SCORE_A, data.getScore(PlayerId.PLAYER_A));
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(#NonNull final Bundle inState) {
super.onRestoreInstanceState(inState);
GameDataInstanceSupplier.restoreInstance(game.getGameData(), inState);
// inside the method the data gets loaded like
// data.setScore(PlayerId.PLAYER_A, inState.getInt(STATE_SCORE_A));
}
I put a "debug output" inside the onCreate() method and it did not appear in the debug log. The same was true for onRestoreInstanceState(). A message was printed inside onSaveInstanceState() when I pushed the home button.
I think your app is not the problem, you see, I came to find this page because I have the same problem switching aplications in my android phone, it's specially noticiable when usig 2 factor authentication and have to switch to text message, mail or other app to get the sent code, when switch back to the code input screen on the browser or app (teams for example) it is no longer there anymore and it has return to the begining, the login screen for example. This is very annoying because I have disable every thing that has to do with energy savings but still have the issue. I discovered that if I open first the message app and then do the authentication while switching very quickly just to see the code in 1 or 2 seconds and then return sometimes it works. It could be memory issue, or may be an unfulfilled politic on the energy savings. I think is probably the last because other explicitly stated properties like setting the screen brightness automatic adjust off and set to maximun works for a while and then returns to a default. It may even be a planned obsolescence. My phone is a Huawei P smart 2019 (POT-LX3) with android 10. I'll may be try a factory reset. Any suggestions are welcome.
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.
I have slight problem. I have gridView in main activity, and on device rotation the list will always start from the top. I fonud several solutions but non of them work for gridView. How can I maintain same gridView position on device rotation using onSavedInstanceState?
Thanks in advance. :)
You first need to understand the facts because of which this is happening. This is happening because whenever your device orientation changes your onDestroy() and onCreate() lifecycle methods are called. To survive your activity state using onSaveInstanceState, you need to save your grid view scroll position when onDestroy() is called and then retrieve it in your onCreate() method. You can do this using Bundle. The code will look something like this, onSaveInstanceState() will be called by android os before your activity get destroyed \n
#Override
onSaveInstanceState(Bundle bundle){
super.onSaveInstanceState(bundle);
bundle.putInt("SCROLL_VIEW_POSITION",scroll_position);
}
//And in your on Create
onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
int scrollPosition = saveInstanceState.get("SCROLL_VIEW_POSITION",default_value);
}
Once you get your same scrollPosition before oreientation change you can use it to set scroll position of your grid view.
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
friends,
i am facing an issue related to android phone screen orientation
If i change the orientation of the phone, then it loses the context, if i am in middle of filling a simple form. So, the phone is vertical, I am using soft keyboard, I make it horizontal, so that I can use the keyboard easily again or something else, and kaboom, everything I have entered so far is lost.
any one guide me what is the solution to keep data and state same after changing orientation?
any help would be appriciated.
That's because activity is actually re-created on orientation change. You have to save your state before the change and then restore it. Override onSaveInstanceState to save your data to bundle. The data is then accessible at onCreate (withing the bundle again).
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable("Key", "Some data"); //put some data
super.onSaveInstanceState(outState);
}