So in order to save the instance of my Fragment, I use a Bundle which I save in onSaveInstanceState and restore in onActivityCreated. Now I'm wondering what the best practice is:
1) Have a bundle where you store variables in, and use/update as required in your code. This way saving and restoring states' code is very short. Something like this:
private Bundle mDataValues = new Bundle();
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if ( (savedInstanceState != null) && (savedInstanceState.getBundle("mDataValues") != null) ) {
this.mDataValues = savedInstanceState.getBundle("mDataValues");
}
public void someFunction() {
if (this.mDataValues == null) {
// Should not be possible on the times we call this function
return;
}
usernameView.setText(mDataValues.getString(Constants.BUNDLE_KEY_USERNAME));
personnameView.setText(mDataValues.getString(Constants.BUNDLE_KEY_PERSONNAME));
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putBundle("mDataValues", mDataValues);
}
2) Have a bunch of variables declared in the fragment, and use these in your code. Something like this:
private String mUsername;
private String mPersonname;
#Override
public void onActivtyCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if ( savedInstanceState != null ) {
mUsername = savedInstanceState.getString("username");
mPersonname = savedInstanceState.getString("personname");
}
}
public void someFunction() {
usernameView.setText(mUsername);
personnameView.setText(mPersonname);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("username", mUsername);
outState.putString("personname", mPersonname);
}
The amount of variables above is of course a lot less than in the actual code written. So what is the best practice? Or are both viable in specific situations?
Related
https://medium.com/#cervonefrancesco/model-view-presenter-android-guidelines-94970b430ddf says to restore state in the model instead of the presenter. What if I have a very simple "model", say a binary toggle that updates a textview to be on or off? Creating a model Toggle class that has a single string value seems like overkill.
Another option is to pass the bundle from my Activity into a corresponding method in my presenter inside onSaveInstanceState and restore it similarly with onCreate. But the article also says that we should avoid having android dependencies in the presenter.
Finally I tried using Icepick but this did not work:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Icepick.restoreInstanceState(this, savedInstanceState);
(Button) findViewById(R.id.btn).setOnClickListener(this);
presenter.onCreate();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Icepick.saveInstanceState(this, outState);
}
#Override
public void onClick(View view) {
presenter.onButtonClicked();
}
#Override
public void updateState(String state) {
tv.setText(state);
}
MainPresenter.java
public class MainPresenter {
private MainView mainView;
#State String toggle;
#Inject
public MainPresenter(MainView mainView) {
this.mainView = mainView;
}
void onCreate() {
mainView.updateState(toggle);
}
void onButtonClicked() {
mainView.updateState(toggle.equals("on") ? "off" : "on");
}
}
What are my options? If I have to use the model approach can I see an example of this for my case?
If you're using annotation processing to maintain the state, it won't automatically populate data into your presenter without Icepick.saveInstanceState(this, outState) which you can't call in the presenter.
#State String toggle;
This line should be present in the activity. Have a method in your presenter to request data by toggle. Something like this:
#State String toggle = "off"; //default value
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Icepick.restoreInstanceState(this, savedInstanceState);
(Button) findViewById(R.id.btn).setOnClickListener(this);
presenter.onCreate();
presenter.setState(toggle)
}
You can store this value as the global variable in the presenter and decide the app flow accordingly.
I am building a memory game app for a java class and i need to save which words are displayed through rotation of the device...the widgets that need to be saved and passed to the new onCreate() method are button widgets that i used setText to display the words that are being shown....can i save and pass the entire state of the application...here is my code that is obviously not working and i was hoping i could get some insight...thanks...here is my code..
private Bundle myBundle = new Bundle();
.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eight);
if(savedInstanceState != null) {
savedInstanceState = myBundle;
}
......
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
myBundle = savedInstanceState;
}
You got the semantics of using the Bundle backwards. You don't ever want to save the Bundle (or overwrite it). Just use it to serialize your own state variables into it and out of it. For example, if you want to preserve two integer variables and a string between a rotation (such that you can re-initialize the view with these members later), you could do the following:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eight);
if(savedInstanceState != null) {
// Restore our member variables that represent activity state right here from the passed in Bundle.
_x = savedInstanceState.getInt("MyApp.X", 0);
_y = savedInstanceState.getInt("MyApp.Y", 0);
_name = savedInstanceState.getString("MyApp.NAME", "player");
// not shown - initializing the view elements with the initialized member variables.
}
......
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// save our activity state by adding our member variables that represent activity state into the Bundle.
savedInstanceState.putInt("MyApp.X", _x);
savedInstanceState.putInt("MyApp.Y", _y);
savedInstanceState.putString("MyApp.NAME", _name);
// call the parent method *after* you have saved your state
super.onSaveInstanceState(savedInstanceState);
}
Bundle also supports arrays of simple types.
In method onSaveInstanceState add values which you want to save like below
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("key","your string here");
}
and inside oncreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState != null ) {
System.out.println(savedInstanceState .getString("key"));
}
}
I have the following (to avoid checking if a fragment is being created newly or just being recreated)
#Override public void onActivityCreated(Bundle args) {
super.onActivityCreated(args);
if (this.getArguments() != null) args = this.getArguments();
// rest of fragment loading goes here
}
Not sure what you are trying to do never seen budle values being overwritten.
If you want some values to be availbale inside fragment pass those values to activity and inside fragment call getActivity().getIntent().getExtra(
Otherwise have a look at code below if want save some fragment data if fragment is destroyed
Inside fragment in onCreate method check if savedInstanceState is null or not
#Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
//fragment recreated
}
}
Save data as follows
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (jsonObject != null) {
outState.putString(Constants.JSON, jsonObject.toString());
}
}
I'm struggling to recover my position in a listview on screen rotation configuration change.
Amongst the many things I've tried I came to this:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState == null) {
...
mVisibleItem = -1;
} else {
if (savedInstanceState.containsKey(LV_VISIBLE_ITEM)) {
mVisibleItem = savedInstanceState.getInt(LV_VISIBLE_ITEM);
}
}
setRetainInstance(true);
}
and here I'm trying to set the position in the listview
#Override
public void onResume() {
super.onResume();
if (mVisibleItem > 0) {
mlvDictionaryIndex.setSelectionFromTop(mVisibleItem, 0);
}
}
However, much to my surprise, after rotating the screen and watching mVisibleItem gets set with the correct value, in onResume I see that mVisibleItem equals -1. How come?
use onSavedInstanceState to write in the bundle the returned value of ListView.onSaveInstanceState(), and restored it onActivityCreated
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mListView != null) {
outState.putParcelable(LISTVIEW_INTERNAL_STATE_KEY, mListView.onSaveInstanceState());
}
}
after the data are reload then you can call
mListView.onRestoreInstanceState(savedInstanceState.getParcelable(LISTVIEW_INTERNAL_STATE_KEY));
Override onSaveInstanceState such as below"
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("pos", pos);
}
Then in your onCreate method have read the savedInstanceState to check if this is an orientation change or a new activity.
private int pos = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
//This is a new activity
}else{
pos = savedInstanceState.getInt("");
}
Now you have the position in the list, and you can scroll to this in configuration change.
Maybe after the data in the listview is reloaded,the code below will work.
mlvDictionaryIndex.setSelectionFromTop(mVisibleItem, 0);
So you can use post() method, just like below:
post(new Runnable() {
public void run() {
mlvDictionaryIndex.setSelectionFromTop(mVisibleItem, 0);
}
});
When the activity gets called for the very first time, it is called with an extra in the intent. The extra is received and stored in the data member:
class EditBlindScheduleActivity extends Activity
{
private BlindSchedule blindSchedule;
protected void onCreate(Bundle savedInstanceState)
{
...
if (savedInstanceState == null) { // Not recreating, first load.
blindSchedule = (BlindSchedule) getIntent().getSerializableExtra("blindSchedule");
}
There is a simple if/else to determine if we have the blindSchedule object or not.
if (blindSchedule == null) {
setTitle("Create Blind Schedule");
} else {
setTitle("Edit Blind Schedule");
}
When I load the activity for the first time, indeed, the title is "Edit Blind Schedule", meaning there is a blindSchedule object.
Unfortunately, when I rotate the screen twice the title reads "Create Blind Schedule", meaning the blindSchedule object is null and has failed to be persisted.
Why is my blindSchedule object not being persisted, and what can I do about it?
Full code follows:
public class EditBlindScheduleActivity extends Activity {
private BlindSchedule blindSchedule;
Boolean creating; // Creating or updating?
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_blind_schedule);
if (savedInstanceState == null) { // Not recreating, first load.
blindSchedule = (BlindSchedule) getIntent().getSerializableExtra("blindSchedule");
}
if (blindSchedule == null) {
creating = true;
setTitle("Create Blind Schedule");
} else {
creating = false;
setTitle("Edit Blind Schedule");
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
blindSchedule = (BlindSchedule) savedInstanceState.getSerializable("blindSchedule");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("blindSchedule", blindSchedule);
}
You need to retrieve the saved custom object in onCreate in your case.
According to Official Documentation
onRestoreInstanceState is called after onStart by which time your setTitle has already been called.
Add an else part to the if (savedInstanceState == null) and retrieve blindSchedule in there same way as you do for your getIntent
if (savedInstanceState == null)
{ // Not recreating, first load.
blindSchedule = (BlindSchedule) getIntent().getSerializableExtra("blindSchedule");
}
else
{
blindSchedule = (BlindSchedule) savedInstanceState.getSerializableExtra("blindSchedule");
}