How can I prevent a Fragment's onCreateView() from being called? - android

So here is my code. 'currentFragment' is simply a field that tracks what is currently being displayed. This is in a class that itself is a Fragment (so I have a fragment showing a fragment).
private void selectNavBarItem(NavbarItem v)
{
Fragment fragmentToUse = null;
if (v == setpointsNavItem)
{
fragmentToUse = setpointsFragment;
}
else if (v == rapidSetupNavItem)
{
fragmentToUse = rapidSetupFragment;
}
else if (v == outdoorResetNavItem)
{
fragmentToUse = outdoorResetFragment;
}
else if (v == rampDelayNavItem)
{
fragmentToUse = rampDelayFragment;
}
if (fragmentToUse != null)
{
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (currentFragment != null)
{
ft.detach(currentFragment);
}
currentFragment = fragmentToUse;
if (currentFragment.isDetached())
{
ft.attach(currentFragment);
}
else
{
ft.add(R.id.setup_content_holder, currentFragment);
}
ft.addToBackStack(null);
ft.commit();
}
Everything looks great, but the views are getting recreated for all the fragments (onCreateView() and onViewCreated()). I was hoping that attaching and detaching would work, but it doesn't. The reason I want to maintain the view is so the user's selections are still there when they navigate back.
Another option is showing and hiding, but I don't know how to make that work because the fragment that owns this code has a FrameLayout (R.id.setup_content_holder) that holds the fragment I want to add, and I can't just add four fragments to it but hide three of them. There is an option to add a fragment with no container, but I have no idea how that is supposed to work.
So, any ideas?

Try this, this will solve your frgment view r-creating issue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (mFragmentView != null) {
((ViewGroup) mFragmentView.getParent()).removeView(mFragmentView);
return mFragmentView;
}
mFragmentView = inflater.inflate(R.layout.home_fragment, container, false);
..... // your remaining code
}

The OnCreateView methods are always called within a Fragment.
To solve the problem you're describing what you really need to do is save the state of the fragment, then when it returns the application will restore what you saved.
e.g. (within the fragment class in question):
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceStatePutString("userString", someTextView.getText().toString());
savedInstanceStatePutInt("userInt", userInt);
// etc...
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
someTextView.setText(savedInstanceState.getString("userString"));
userInt = savedInstanceState.getInt("userInt");
}
That should solve your problem while hopping between fragments; the application will call onSaveInstanceState and onRestoreInstanceState when a fragment gets pushed into or pulled out of the stack.
It will not save them forever, however! If you need more persistent storage, look into other options such as saving to a sqlite database.

OP here.
So I hacked something together here, and I'm wondering if it's a good idea. I have a Fragment holding a View. The View contains everything I want to save (in the short term, of course - this isn't supposed to be any more persistent than RAM). When the Fragment calls onCreateView() I simply return the already-created View.
Now, I ran into an issue where the View was not being removed by the fragment manager. I added a call in onPause() to make sure it's removed from the parent.
Everything seems to work fine, but I want to make sure I'm not doing something really bad. I know Android really really wants to manage its view lifecycles itself, but I do not want it recreating them every damn time. They are complicated and I don't want to deal with re-initializing all the subview text/image/state. Will I run into issues in my attempt to do a run-around Android's normal operating procedure?
EDIT: forgot the code:
public class OutdoorResetFragment extends Fragment
{
private OutdoorResetView view;
public OutdoorResetFragment()
{
}
public void onAttach(Activity activity)
{
if (view == null || view.getContext() != activity)
{
view = new OutdoorResetView(activity);
}
super.onAttach(activity);
}
public void onPause()
{
super.onPause();
ViewGroup container = (ViewGroup) view.getParent();
if (container != null)
{
container.removeAllViews();
}
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState)
{
return view;
}
public OutdoorResetView getView()
{
return view;
}
}

Related

Android-Save state of Fragment with RecyclerView [duplicate]

I've written up a dummy activity that switches between two fragments. When you go from FragmentA to FragmentB, FragmentA gets added to the back stack. However, when I return to FragmentA (by pressing back), a totally new FragmentA is created and the state it was in is lost. I get the feeling I'm after the same thing as this question, but I've included a complete code sample to help root out the issue:
public class FooActivity extends Activity {
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, new FragmentA());
transaction.commit();
}
public void nextFragment() {
final FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, new FragmentB());
transaction.addToBackStack(null);
transaction.commit();
}
public static class FragmentA extends Fragment {
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View main = inflater.inflate(R.layout.main, container, false);
main.findViewById(R.id.next_fragment_button).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((FooActivity) getActivity()).nextFragment();
}
});
return main;
}
#Override public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save some state!
}
}
public static class FragmentB extends Fragment {
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.b, container, false);
}
}
}
With some log messages added:
07-05 14:28:59.722 D/OMG ( 1260): FooActivity.onCreate
07-05 14:28:59.742 D/OMG ( 1260): FragmentA.onCreateView
07-05 14:28:59.742 D/OMG ( 1260): FooActivity.onResume
<Tap Button on FragmentA>
07-05 14:29:12.842 D/OMG ( 1260): FooActivity.nextFragment
07-05 14:29:12.852 D/OMG ( 1260): FragmentB.onCreateView
<Tap 'Back'>
07-05 14:29:16.792 D/OMG ( 1260): FragmentA.onCreateView
It's never calling FragmentA.onSaveInstanceState and it creates a new FragmentA when you hit back. However, if I'm on FragmentA and I lock the screen, FragmentA.onSaveInstanceState does get called. So weird...am I wrong in expecting a fragment added to the back stack to not need re-creation? Here's what the docs say:
Whereas, if you do call addToBackStack() when removing a fragment,
then the fragment is stopped and will be resumed if the user navigates
back.
If you return to a fragment from the back stack it does not re-create the fragment but re-uses the same instance and starts with onCreateView() in the fragment lifecycle, see Fragment lifecycle.
So if you want to store state you should use instance variables and not rely on onSaveInstanceState().
Comparing to Apple's UINavigationController and UIViewController, Google does not do well in Android software architecture. And Android's document about Fragment does not help much.
When you enter FragmentB from FragmentA, the existing FragmentA instance is not destroyed. When you press Back in FragmentB and return to FragmentA, we don't create a new FragmentA instance. The existing FragmentA instance's onCreateView() will be called.
The key thing is we should not inflate view again in FragmentA's onCreateView(), because we are using the existing FragmentA's instance. We need to save and reuse the rootView.
The following code works well. It does not only keep fragment state, but also reduces the RAM and CPU load (because we only inflate layout if necessary). I can't believe Google's sample code and document never mention it but always inflate layout.
Version 1(Don't use version 1. Use version 2)
public class FragmentA extends Fragment {
View _rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (_rootView == null) {
// Inflate the layout for this fragment
_rootView = inflater.inflate(R.layout.fragment_a, container, false);
// Find and setup subviews
_listView = (ListView)_rootView.findViewById(R.id.listView);
...
} else {
// Do not inflate the layout again.
// The returned View of onCreateView will be added into the fragment.
// However it is not allowed to be added twice even if the parent is same.
// So we must remove _rootView from the existing parent view group
// (it will be added back).
((ViewGroup)_rootView.getParent()).removeView(_rootView);
}
return _rootView;
}
}
------Update on May 3 2005:-------
As the comments mentioned, sometimes _rootView.getParent() is null in onCreateView, which causes the crash. Version 2 removes _rootView in onDestroyView(), as dell116 suggested. Tested on Android 4.0.3, 4.4.4, 5.1.0.
Version 2
public class FragmentA extends Fragment {
View _rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (_rootView == null) {
// Inflate the layout for this fragment
_rootView = inflater.inflate(R.layout.fragment_a, container, false);
// Find and setup subviews
_listView = (ListView)_rootView.findViewById(R.id.listView);
...
} else {
// Do not inflate the layout again.
// The returned View of onCreateView will be added into the fragment.
// However it is not allowed to be added twice even if the parent is same.
// So we must remove _rootView from the existing parent view group
// in onDestroyView() (it will be added back).
}
return _rootView;
}
#Override
public void onDestroyView() {
if (_rootView.getParent() != null) {
((ViewGroup)_rootView.getParent()).removeView(_rootView);
}
super.onDestroyView();
}
}
WARNING!!!
This is a HACK! Though I am using it in my app, you need to test and read comments carefully.
I guess there is an alternative way to achieve what you are looking for.
I don't say its a complete solution but it served the purpose in my case.
What I did is instead of replacing the fragment I just added target fragment.
So basically you will be going to use add() method instead replace().
What else I did.
I hide my current fragment and also add it to backstack.
Hence it overlaps new fragment over the current fragment without destroying its view.(check that its onDestroyView() method is not being called. Plus adding it to backstate gives me the advantage of resuming the fragment.
Here is the code :
Fragment fragment=new DestinationFragment();
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction ft=fragmentManager.beginTransaction();
ft.add(R.id.content_frame, fragment);
ft.hide(SourceFragment.this);
ft.addToBackStack(SourceFragment.class.getName());
ft.commit();
AFAIK System only calls onCreateView() if the view is destroyed or not created.
But here we have saved the view by not removing it from memory. So it will not create a new view.
And when you get back from Destination Fragment it will pop the last FragmentTransaction removing top fragment which will make the topmost(SourceFragment's) view to appear over the screen.
COMMENT: As I said it is not a complete solution as it doesn't remove the view of Source fragment and hence occupying more memory than usual. But still, serve the purpose. Also, we are using a totally different mechanism of hiding view instead of replacing it which is non traditional.
So it's not really for how you maintain the state, but for how you maintain the view.
I would suggest a very simple solution.
Take the View reference variable and set view in OnCreateView. Check if view already exists in this variable, then return same view.
private View fragmentView;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (fragmentView != null) {
return fragmentView;
}
View view = inflater.inflate(R.layout.yourfragment, container, false);
fragmentView = view;
return view;
}
I came across this problem in a Fragment containing a map, which has too many setup details to save/reload.
My solution was to basically keep this Fragment active the whole time (similar to what #kaushal mentioned).
Say you have current Fragment A and wants to display Fragment B.
Summarizing the consequences:
replace() - remove Fragment A and replace it with Fragment B. Fragment A will be recreated once brought to the front again
add() - (create and) add a Fragment B and it overlap Fragment A, which is still active in the background
remove() - can be used to remove Fragment B and return to A. Fragment B will be recreated when called later on
Hence, if you want to keep both Fragments "saved", just toggle them using hide()/show().
Pros: easy and simple method to keep multiple Fragments running
Cons: you use a lot more memory to keep all of them running. May run into problems, e.g. displaying many large bitmaps
onSaveInstanceState() is only called if there is configuration change.
Since changing from one fragment to another there is no configuration change so no call to onSaveInstanceState() is there. What state is not being save? Can you specify?
If you enter some text in EditText it will be saved automatically. Any UI item without any ID is the item whose view state shall not be saved.
first: just use add method instead of replace method of FragmentTransaction class then you have to add secondFragment to stack by addToBackStack method
second :on back click you have to call popBackStackImmediate()
Fragment sourceFragment = new SourceFragment ();
final Fragment secondFragment = new SecondFragment();
final FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.add(R.id.child_fragment_container, secondFragment );
ft.hide(sourceFragment );
ft.addToBackStack(NewsShow.class.getName());
ft.commit();
((SecondFragment)secondFragment).backFragmentInstanceClick = new SecondFragment.backFragmentNewsResult()
{
#Override
public void backFragmentNewsResult()
{
getChildFragmentManager().popBackStackImmediate();
}
};
Kotlin and ViewBinding Solution
I am using replace() and backstack() method for FragmentTransaction. The problem is that the backstack() method calls the onCreateView of the Previous Fragment which causes in re-built of Fragment UI. Here is a solution for that:
private lateinit var binding: FragmentAdRelevantDetailsBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?
): View {
if (!this::binding.isInitialized)
binding = FragmentAdRelevantDetailsBinding.inflate(layoutInflater, container, false)
return binding.root
}
Here, since onSaveInstanceState in fragment does not call when you add fragment into backstack. The fragment lifecycle in backstack when restored start onCreateView and end onDestroyView while onSaveInstanceState is called between onDestroyView and onDestroy. My solution is create instance variable and init in onCreate. Sample code:
private boolean isDataLoading = true;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
isDataLoading = false;
// init list at once when create fragment
listData = new ArrayList();
}
And check it in onActivityCreated:
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(isDataLoading){
fetchData();
}else{
//get saved instance variable listData()
}
}
private void fetchData(){
// do fetch data into listData
}
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener()
{
#Override
public void onBackStackChanged()
{
if (getSupportFragmentManager().getBackStackEntryCount() == 0)
{
//setToolbarTitle("Main Activity");
}
else
{
Log.e("fragment_replace11111", "replace");
}
}
});
YourActivity.java
#Override
public void onBackPressed()
{
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.Fragment_content);
if (fragment instanceof YourFragmentName)
{
fragmentReplace(new HomeFragment(),"Home Fragment");
txt_toolbar_title.setText("Your Fragment");
}
else{
super.onBackPressed();
}
}
public void fragmentReplace(Fragment fragment, String fragment_name)
{
try
{
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.Fragment_content, fragment, fragment_name);
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
fragmentTransaction.addToBackStack(fragment_name);
fragmentTransaction.commitAllowingStateLoss();
}
catch (Exception e)
{
e.printStackTrace();
}
}
My problem was similar but I overcame me without keeping the fragment alive. Suppose you have an activity that has 2 fragments - F1 and F2. F1 is started initially and lets say in contains some user info and then upon some condition F2 pops on asking user to fill in additional attribute - their phone number. Next, you want that phone number to pop back to F1 and complete signup but you realize all previous user info is lost and you don't have their previous data. The fragment is recreated from scratch and even if you saved this information in onSaveInstanceState the bundle comes back null in onActivityCreated.
Solution:
Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
// this will be null the first time F1 is created.
// it will be populated once you replace fragment and provide bundle data
if (args != null) {
if (args.get("your_info") != null) {
// do what you want with restored information
}
}
}
So following on with my example: before I display F2 I save user data in the instance variable using a callback. Then I start F2, user fills in phone number and presses save. I use another callback in activity, collect this information and replace my fragment F1, this time it has bundle data that I can use.
#Override
public void onPhoneAdded(String phone) {
//replace fragment
F1 f1 = new F1 ();
Bundle args = new Bundle();
yourInfo.setPhone(phone);
args.putSerializable("you_info", yourInfo);
f1.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, f1).addToBackStack(null).commit();
}
}
More information about callbacks can be found here: https://developer.android.com/training/basics/fragments/communicating.html
Replace a Fragment using following code:
Fragment fragment = new AddPaymentFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment, "Tag_AddPayment")
.addToBackStack("Tag_AddPayment")
.commit();
Activity's onBackPressed() is :
#Override
public void onBackPressed() {
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 1) {
fm.popBackStack();
} else {
finish();
}
Log.e("popping BACKSTRACK===> ",""+fm.getBackStackEntryCount());
}
Public void replaceFragment(Fragment mFragment, int id, String tag, boolean addToStack) {
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
mTransaction.replace(id, mFragment);
hideKeyboard();
if (addToStack) {
mTransaction.addToBackStack(tag);
}
mTransaction.commitAllowingStateLoss();
}
replaceFragment(new Splash_Fragment(), R.id.container, null, false);
Perfect solution that find old fragment in stack and load it if exist in stack.
/**
* replace or add fragment to the container
*
* #param fragment pass android.support.v4.app.Fragment
* #param bundle pass your extra bundle if any
* #param popBackStack if true it will clear back stack
* #param findInStack if true it will load old fragment if found
*/
public void replaceFragment(Fragment fragment, #Nullable Bundle bundle, boolean popBackStack, boolean findInStack) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
String tag = fragment.getClass().getName();
Fragment parentFragment;
if (findInStack && fm.findFragmentByTag(tag) != null) {
parentFragment = fm.findFragmentByTag(tag);
} else {
parentFragment = fragment;
}
// if user passes the #bundle in not null, then can be added to the fragment
if (bundle != null)
parentFragment.setArguments(bundle);
else parentFragment.setArguments(null);
// this is for the very first fragment not to be added into the back stack.
if (popBackStack) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
ft.addToBackStack(parentFragment.getClass().getName() + "");
}
ft.replace(R.id.contenedor_principal, parentFragment, tag);
ft.commit();
fm.executePendingTransactions();
}
use it like
Fragment f = new YourFragment();
replaceFragment(f, null, boolean true, true);
Calling the Fragment lifecycle methods properly and using onSavedInstanceState() can solve the problem.
i.e Call onCreate(), onCreateView(), onViewCreated() and onSavedInstanceState() properly and save Bundle in onSaveInstanceState() and resotre it in onCreate() method.
I don't know how but it worked for me without any error.
If anyone can explain it will very much appreciated.
public class DiagnosisFragment extends Fragment {
private static final String TITLE = "TITLE";
private String mTitle;
private List mList = null;
private ListAdapter adapter;
public DiagnosisFragment(){}
public DiagnosisFragment(List list, String title){
mList = list;
mTitle = title;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
mList = savedInstanceState.getParcelableArrayList(HEALTH_ITEMS);
mTitle = savedInstanceState.getString(TITLE);
itemId = savedInstanceState.getInt(ID);
mChoiceMode = savedInstanceState.getInt(CHOICE_MODE);
}
getActivity().setTitle(mTitle);
adapter = (ListAdapter) new HealthAdapter(mList, getContext()).load(itemId);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.diagnosis_fragment, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView lv = view.findViewById(R.id.subLocationsSymptomsList);
lv.setAdapter(adapter);
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
outState.putParcelableArrayList(HEALTH_ITEMS, (ArrayList) mList);
outState.putString(TITLE, mTitle);
}
}
For who has looking for solution :
#Override
public void onDestroyView() {
Bundle savedState=new Bundle();
// put your data in bundle
// if you have object and want to restore you can use gson to convert it
//to sring
if (yourObject!=null){
savedState.putString("your_object_key",new Gson().toJson(yourObject));
}
if (getArguments()==null){
setArguments(new Bundle());
}
getArguments().putBundle("saved_state",savedState);
super.onDestroyView();
}
and in onViewCreated() method :
Bundle savedState=null;
if (getArguments()!=null){
savedState=getArguments().getBundle("saved_state");
}
if (savedState!=null){
// set your restored data to your view
}

android fragment destroyed after home or overview buttons are pressed

I'm fairly new to android programming, so please bear with me. I've tried searching all over SO, tutorialspoint, big nerd ranch, etc, but I'm not finding/understanding this: how do I make a fragment persist after a user has pressed the home or overview buttons? For example:
I have two fragments A and B in an activity with a toggle button to switch between the two fragments. By default, fragment A loads on the screen when the activity is created. If I toggle to fragment B and press either home or overview and then return to the app, fragment A is displayed. I understand why it's displaying, but what I don't understand is how to keep fragment B displayed.
I've read about the backstack, savedInstanceState, and setRetainInstance (among several others), but haven't been able to figure it out.
I'm overriding onAttach(Context context), onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState), and onViewCreated(View view, Bundle savedInstanceState) in both fragments, and onStart() and onCreate(Bundle savedInstanceState) in my activity.
fragments:
#Override
public void onAttach(Context context) {
this.context = context;
faContext = (FragmentActivity) context;
super.onAttach(context);
}// end onAttach(Activity activity)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
if(bundle != null) {
String bundleAdminId = getString(R.string.bundle_admin_name);
adminName = bundle.getString(bundleAdminId);
}
else {
Log.d("BUNDLE_Profile", "bundle is null");
}
// Defines the xml file for the fragment
return inflater.inflate(R.layout.fragment_profile, parent, false);
}// end onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
onViewCreated only has button event handlers
activity:
#Override
public void onStart() {
super.onStart();
// start the home fragment
createFragment(new HomeFragment(), R.id.frag_container);
// update the local storage
}// end onStart()
private void createFragment(Fragment fragment, int fragContainerId) {
// make sure the passed fragment isn't null
if(fragment != null) {
FragmentTransaction ft = faContext.getSupportFragmentManager().beginTransaction();
ft.replace(fragContainerId, fragment);
ft.commit();
}
}// end createFragment(Fragment fragment)`
onCreate also has button handlers
Use tags to open a fragment.Try this function
public void openNewFragment(Fragment f, String tag) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
{
if (fragment != null) {
if (currentFragment != null) {
if (fragment.getClass().equals(currentFragment.getClass())) {
drawerLayout.closeDrawers();
return;
}
}
ft.show(fragment);
ft.hide(currentFragment);
currentFragment = fragment;
} else {
if (currentFragment != null)
ft.hide(currentFragment);
ft.add(R.id.container, f, tag);
currentFragment = f;
}
ft.commit();
}
}
In this function you have to provide fragment name and its tag.
You cannot retain the fragment position when re-launching app unless it is stored. So one way could be while switching between the fragments, store the current position of fragment in Shared Preference.While restarting the application read the previously stored fragment position and update SharedPreferences value when switched.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("fragmentPosition",MODE_PRIVATE);
if(sharedPreferences.getInt("position",0)==1) loadFragmentOne();
else loadFragmentTwo();
}
public void onToggleMethod(){
if(currentToggle ==1){
LoadFragmentTwo();
UpdateSharedPreference();
}
else{
loadFragmentOne();
UpdateSharedPreference();
}
}
Obviously the activity goes to the stopped mode and getting started when you return back to the activity from home after some time. May be because of the resources are freed from the memory.
To know more better on this just try to be on fragment b and immediately make the home press and again come back to app through the recent apps section and see the behavior.
Also if the problem is what i have stated above then.. try following
Try creating a variable that is static and try to remember the last loaded fragment and in the on resume of the activity load the fragment which was last loaded.
Else in the onstart load the fragment the using the fragment manager with a tag and also put a condition before the loading to check whether the fragment is alredy in memory if so dont load anything.
Something like this..
onStart(){
if(fragmentManager.getFragmentByTag("String tag")== null){
createFragment();
}
}
Try and let me know if this is useful.
Try to Change the onStart method like this ,
#Override
public void onStart() {
super.onStart();
// start the home fragment
if(faContext.getSupportFragmentManager().findFragmentById(R.id.frag_container) == null) {
createFragment(new HomeFragment(), R.id.frag_container);
}
// update the local storage
}// end onStart()

Fragment in viewpager savedinstancestate is always null

I know this question has been asked before but none of the answers given so far is of any help to me.
I have a viewpager which is populated with fragments (android.support.v4.app.Fragment) from a FragmentStatePagerAdapter . Some of these fragments contain logic that needs to be retained when the orientation changes, such as keeping track of which view is currently selected.
However, although I save the data in question in onSaveInstanceState the savedInstanceState is always null. I can solve this by storing the data in a static variable (which since I only have one instance of each fragment would work for me) but i found this to be a quite ugly solution and there has to be a proper way of doing this.
This is one of the fragments that doesn't retain it's state on rotation:
public class PriceSelectFragment extends Fragment {
private TableRow mSelected;
private int mSelectedPos = 0;
// newInstance constructor for creating fragment with arguments
public static PriceSelectFragment newInstance() {
PriceSelectFragment fragmentFirst = new PriceSelectFragment();
return fragmentFirst;
}
public PriceSelectFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_price_select, container, false);
TableLayout mTable = (TableLayout)view.findViewById(R.id.price_table);
List<PriceGroup> mPriceGroups = ((MainActivity) getActivity()).getPriceGroups();
int i = 0;
for (final PriceGroup group : mPriceGroups) {
//Create row from layout and access child TextViews
TableRow r = (TableRow)inflater.inflate( R.layout.price_group, mTable, false);
TextView size = (TextView)r.getChildAt(0);
TextView dimension = (TextView)r.getChildAt(1);
TextView weight = (TextView)r.getChildAt(2);
TextView price = (TextView)r.getChildAt(3);
//Populate row with PriceGroup Data
size.setText(group.sizeIndicator);
dimension.setText(String.format("%2.0fx%2.0fx%2.0f", group.length, group.width, group.height));
weight.setText(Float.toString(group.weight));
price.setText(Integer.toString(group.price));
//Alternate background color every other row
if (i % 2 == 0) {
r.setBackgroundDrawable(getResources().getDrawable(R.drawable.price_selector_1));
}
else {
r.setBackgroundDrawable(getResources().getDrawable(R.drawable.price_selector_2));
}
mTable.addView(r); // Add to table
r.setTag(i);
r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectRow((TableRow) v);
}
});
i++;
}
mSelected = (TableRow)view.findViewWithTag(mSelectedPos);
selectRow(mSelected);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("selected", mSelectedPos);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mSelectedPos = savedInstanceState.getInt("selected");
}
}
private void selectRow(TableRow row) {
if ((int) mSelected.getTag() % 2 == 0) {
mSelected.setBackgroundDrawable(getResources().getDrawable(R.drawable.price_selector_1));
}
else {
mSelected.setBackgroundDrawable(getResources().getDrawable(R.drawable.price_selector_2));
}
mSelected = row;
mSelectedPos = (int) mSelected.getTag();
mSelected.setBackgroundColor(getResources().getColor(R.color.light_blue));
}
}
How do I solve this without having to save my states in static variables?
Edit
I should point out that all of the fragments are programatically created and as such they do not have an id and I read that that might be the problem but I don't know how to solve that either.
Also my application is structured like this:
MainActivity with NavigationDrawer
Fragment1
ViewPager
subfragment1 - subfragment5
Fragment2
Fragment3
The fragments whose states I'm having trouble with are the subfragments.
In your Activity which is hosting your Fragment you need to store a refernce to the fragment in the Bundle.
Something like this should work for you
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
//Restore your fragment instance
fragment1 = getSupportFragmentManager().getFragment(
savedInstanceState, "fragment");
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "fragment", fragment1);
}
fragment1 is the instance of the Fragment1 that you mentioned in your question that needs to get recreated.
I haven't done this with a structure like yours before but this is how I would start:
In the onSaveInstanceState in your Fragment1 I believe you would need to do the same with each of the fragments in your ViewPager. Then in the onCreateView on your Fragment1 get the fragments from the fragment manager and recreate your ViewPager.
I have found this answer here which is pretty much the same but has a little more detail: https://stackoverflow.com/a/17135346/1417483
FragmentPagerAdapter is not calling onSaveInstanceState in frgments that are not visible anymore. Maybe this is what causing your issues.
Try to use FragmentStatePagerAdapter instead.
I finally got a solution and explanation why this is happening. I had a very similar problem. I recognized that when I was scrolling right to my 3rd subfragment and then back to the 1st then the state of the 1st got saved. But not on Orientation Change.
I figured that the state is only saved if the adapter's destroyItem(..) is called. That is not called automatically if orientation changes.
So now onSaveInstanceState of the MainFragment (which holds the ViewPager) I call destroyItem for each active fragment. I check for activity.isChangingConfigurations() because onSaveInstanceState is called too if I turn off the screen, but in that case all the fragments just stay active and nothing has to be changed.
I extended the adapter with an onDestroy(boolean retain) which is called then:
//in the main-fragment which holds the ViewPager:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(getActivity()!=null && getActivity().isChangingConfigurations())
{
if (pager != null) {
try {
Log.w(TAG, TAG + " pager.onDestroy(true)");
pager.onDestroy(true);
} catch (Exception e) {
e.printStackTrace();
}
}
And the implementation in MyFragmentStatePagerAdapter:
public void onDestroy(boolean retain)
{
this.m_allowDynamicLoading = false;
if(retain)
{
try{
if(getAdapter()!=null)
{
int limit = this.getOffscreenPageLimit();
int currentIndex = this.getCurrentItem();
if(currentIndex <0 || getAdapter().getCount() <= 0)
return;
//active fragments = fragments that are (less or equal) then
//offscreenPageLimit awaw from the currently displayed one.
for(int i = Math.min(currentIndex+limit, getAdapter().getCount()-1);
i>= Math.max(0, currentIndex-limit);//erstes aktives fragment ist current - offscreen limit, aber nicht unter 0..
i--)
{
getAdapter().destroyItem(MessagingViewPager.this, i, getAdapter().instantiateItem(MessagingViewPager.this, i)); //this saved the state of that fragment, that will be restored after orientation change
Log.e(TAG,TAG + " orientation-change: destroying item " + i);
}
}
}catch(Exception e){}
}
else{ //retain = false is called onDestroy of the Fragment holding this Pager.
try{
this.setAdapter(null);
//this will destroy all fragments and forget the position
}catch(Exception e){}
}
}
Some other things are to be said:
Adapter takes the ChildFragmentManager not the normal one
The SubFragments must NOT use setRetainInstance(true) (Exception otherwise)
The MainFragment can (and in my case does) use setRetainInstance(true)
Create the adapter in onCreate of the MainFragment, so it will NOT be recreated on Orientation change. Setting adapter to pager should be done in onCreateView.
OnDestroy (or onDestroyView) of the MainFragment use setAdapter(null) to terminate all fragments and release resources. (This is done by MyViewPager.onDestroy(false) in my case)
et voiĆ”: now you get your savedInstanceState bundle in the SubFragments after the orientation change. And it will not destroy the items if you only switch the screen off.

Fragment View State on Screen Rotation

I have a few fragments that are loaded when a user clicks on an item in a list. Say a user has clicked on second item in the list, loading the second fragment. But, upon rotating, the screen, the first fragment in the list gets loaded. How can I make sure that the same fragment gets loaded whenever a user rotates the screen.
This is how I'm loading my fragments
private void selectItem(position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
else {
Log.e("NavigationActivity", "Error in creating fragment");
}
}
I'm calling selectItem(0) in onCreate of an activity.
The entire activity gets destroyed and recreated during a rotation. So if you are calling setItem(0) in Activity.onCreate, then you'll always get FirstFragment in the content frame.
Seems like the easy thing may be to just detect if you've already set a fragment in onCreate and not load the default. Either make use of onSaveInstanceState and/or mark the fragment as retained.
I don't have much experience with retained fragments or fragment management beyond initial load, so just using onSaveInstanceState to keep track of which one was loaded seems appropriate.
In your Activity, override onSaveInstanceState:
#Override
public void onSaveInstanceState(Bundle bundle)
{
bundle.putInt("which_fragment", _fragmentId);
super.onSaveInstanceState(bundle);
}
Where _fragmentId is just some numerical identifier of the particular fragment you are loading. It could even be it's layout id. Set this value in your selectItem method.
And then in onCreate:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
_fragmentId = 0;
if (savedInstanceState != null)
{
_fragmentId = savedInstanceState.getInt("which_fragment", 0);
}
...
selectItem(_fragmentId);
}
First of all I wouldn't use positionOnTheList->Fragment dependency. I would depend on some id (final or from the resources).
Secondly I think you shouldn't create a new instance of each Fragment class when you select item from the list.
You should consider this approach:
Fragment f = fragmentManager.findFragmentById( String.valueOf(id) );
if( f == null )
f = new FragmentDependingOnId();
mCurrentlySelectedId = id;
fragmentManager.beginTransaction()
.replace( R.id.container, f , String.valueOf(id))
.commit();
Add the following method:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SELECTED_ID, mCurrentlySelectedId);
}
and in onCreate add:
if(savedInstanceState!=null){
mCurrentlySelectedId = savedInstanceState.getInt(SELECTED_ID);
selectItem(mCurrentlySelectedId);
}
When using fragment you usually use onCreateView to inflate your layout. Then you use onActivityCreated to do all the stuff you need to init listviews etc ...
In your case the problem you have is that you should use the saveInstanceState to keep track of if a fragment is loaded or not because the fragment is re-created on each rotation.
Let's look at some code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_fragment_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
//do nothing if the state already exists
} else {
//do something if state already exists
}
}
Note that if you need to save a given value, for example a boolean you can use
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(YOUR_BOOL_TAG, mYourBooleanVar);
}
and get it back in the onCreateView by using
mYourBooleanVar= savedInstanceState.getBoolean(YOUR_BOOL_TAG);
same applies to other types also.
EDIT
I didn't quite answered your question, so I put more details. The above code is in the fragment. However for your question, in the activity you need something like that.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
//here is the transaction to load your first fragment
}
}
and your first fragement won't reload each time.
The first time savedInstanceState will be null and you set your default fragment. Then each time you rotate savedInstanceState is not null and your default fragment is not reloaded but the one that is currently present.
Only this code is relevant for you, but I let the code above the EDIT for other people in case it can be useful to them.

Fragments view is null when orientation changed

Im having some problems when it comes to porting my app from the normal activity style to the fragment style. Im beginning to notice that when a fragment gets recreated, or popped from the backstack it loses its views. When I say that Im talking about a listview in particular. What im doing is im loading items into the listview, then rotating the screen. When it goes back through, it gets a nullpointerexception. I debug it and sure enough the listview is null. Here is the relevant code to the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
return inflater.inflate(R.layout.sg_question_frag, viewGroup, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
list = (ListView)getActivity().findViewById(R.id.sgQuestionsList);
if (savedInstanceState != null) {
catId = savedInstanceState.getInt("catId");
catTitle = savedInstanceState.getString("catTitle");
}
populateList(catId, catTitle);
}
And here is how it is called (keep in mind there are a few other fragments that im working with as well)
#Override
public void onTopicSelected(int id, String catTitle) {
// TODO Auto-generated method stub
FragmentManager fm = this.getSupportFragmentManager();
SGQuestionFragment sgQuestFrag = (SGQuestionFragment) fm.findFragmentByTag("SgQuestionList");
FragmentTransaction ft = fm.beginTransaction();
//If the fragment isnt instantiated
if (sgQuestFrag == null) {
sgQuestFrag = new SGQuestionFragment();
sgQuestFrag.catId = id;
sgQuestFrag.catTitle = catTitle;
//Fragment isnt there, so we have to put it there
if (mDualPane) {
//TO-DO
//If we are not in dual pane view, then add the fragment to the second container
ft.add(R.id.sgQuestionContainer, sgQuestFrag,"SgQuestionList").commit();
} else {
ft.replace(R.id.singlePaneStudyGuide, sgQuestFrag, "SqQuestionList").addToBackStack(null).commit();
}
} else if (sgQuestFrag != null) {
if (sgQuestFrag.isVisible()) {
sgQuestFrag.updateList(id, catTitle);
} else {
sgQuestFrag.catId = id;
sgQuestFrag.catTitle = catTitle;
ft.replace(R.id.sgQuestionContainer, sgQuestFrag, "SgQuestionList");
ft.addToBackStack(null);
ft.commit();
sgQuestFrag.updateList(id, catTitle);
}
}
fm.executePendingTransactions();
}
What I would ultimately want it to do is to completely recreate the activity, forget the fragments and everything and just act like the activity was started in landscape mode or portrait mode. I dont really need the fragments there, I can recreate them progmatically with some saved variables
If you want to get a reference to a view from within a Fragment always look for that View in the View returned by the getView() method. In your case, at the time you look for the ListView the Fragment's view probably isn't yet attached to the activity so the reference will be null. So you use:
list = (ListView) getView().findViewById(R.id.sgQuestionsList);

Categories

Resources