Reputation: 3316
I have two fragments FragmentA and FragmentB. From Fragment A i update Views in Fragment B by passing custom object as a parameter to a method in Fragment B. For example below is the Fragment B:
public class FragmentB extends Fragment {
private ArrayList<String> customObj = new ArrayList<String>();
public void updateViews(ArrayList<String> obj) {
customObj = obj;
}
@Override
public void onSaveInstanceState(Bundle outState) {
System.out.println("Custom Object : "+customObj);//custom object is always empty
}
Now, whenever i rotate the screen, the custom object is al;ways empty.
Note Here I am just updating the views of Fragement B. The object is passed as a parameter from Fragment A to the method updateViews of Fragment B. Also, i am not looking forward to define static for custom object.
Upvotes: 0
Views: 4719
Reputation: 13384
You can do two things 1. Store that custom object somewhere which is not created every time orientation is changed i.e. Application class, Service etc. 2. Store that object inside the Bundle which you get as a parameter inside OnSaveInstanceState() and use that Bundle to set the Object in OnRestoreInstanceState() or OnCreate()...
For Example,
@Override
protected void onCreate(Bundle savedInstanceState) {
Logger.d("Dash onCreate");
super.onCreate(savedInstanceState);
...
// create fragments to use
if (savedInstanceState != null) {
//get your Object
}
if (yourObject != null)
//restore the View using yourObject
...
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
Now in your Custom Class you will have to either implement Serializable or Parcelable for storing that inside a Bundle. Serialization is simple but if you implement Parcellable you have more control on it.
Some other similar threads on SO related to this topic are
You can get a similar Example in Android Documentations for Fragments.
Upvotes: 2