understanding Fragment replacement using FragmentPagerAdapter - java

I'm having a hard time understanding how to replace fragments using the FragmentPagerAdapter. I have a class that extends FragmentPagerAdapter (android.support.v13.app.FragmentPagerAdapter) and my MainActivity implements ActionBar.TabListener, in the FragmentPageAdapter class I use the getItem() to setup my 3 fragments. so far so good.
One of these fragments is a ListView (pos #1), which I use a Listener to check on the onItemClick().
I want to replace the current ListView Fragment with another fragment so what I did is that inside the onItemClick() I perform the following code:
FragmentManager mFragmentManager = mActivity.getFragmentManager();
//new fragment to replace
Fragment mFragment = new TabPlaceFragment();
mFragmentManager.beginTransaction()
.replace(R.id.pager, mFragment)
.addToBackStack(null)
.commit();
What this is doing is that the fragment is replace with a blank fragment, I'm assuming is the pager, but the mFragment does not get replace. I tried giving an Id to the Current fragment and tried replacing it.
mFragmentManager.beginTransaction()
.replace(R.id.frament_old, mFragment)
.addToBackStack(null)
.commit();
But what this does is that it overlaps the new fragment on top of the old fragment
finally I tried getting the Id of the fragment to replace with the new, but this also gave me a blank fragment.
//this gives me the current fragment I want to replace
Fragment mCurrent = mFragmentManager.findFragmentByTag(MainHelper.getFragmentName(mViewPager.getId(), 1));
mFragmentManager.beginTransaction()
.replace(mCurrent.getId(), mFragment)
.addToBackStack(null)
.commit();
I'm sure I'm not implementing the method correctly but I cannot find a good example to follow the logic of my code. I thought of putting the fragment replacement in the MainActivity under getItem(), but don't know how to call it from within my onItemClick() Listener.
Any help is highly appreciated!!!
Thanks.

Related

How to run a function in a created fragment?

I have a Fragment (MapsCoverFragment) which has a FrameLayout in which I launch another Fragment (MapsFragment) with code like this:
// in Class begining
private Fragment mapsFragment;
// in onCreateView()
mapsFragment = new MapsFragment();
getParentFragmentManager()
.beginTransaction()
.replace(R.id.mapsFrame, mapsFragment)
.commit();
In MapsFragment() I have a function:
public void getChargePoints() {...}
That is, I have access to the created MapsFragment through the measured mapsFragment.
How do I run getChargePoints() from MapsCoverFragment?
private Fragment mapsFragment;
That's all I needed to do. I declared the wrong class.

Using ViewModel to get Live Data in Android Fragment

I need to observe livedata changes in a Modelview to update a fragment (Adding the list to a recyclerview).
The implementation is working correctly but facing problems when switching between fragments.
If the implementation is on Fragment A when the user switches to Fragment B and then back to Fragment A a second livedata observer gets initiated. (Data in recyclerview gets duplicated) and so on...
I did some research on the Fragment Lifecycle and the need to remove the observer when moving between fragments (Either on Fragment Detach/Destroy) or before creating a new observer in the OnActivityCreated. But any of these worked.
I am observing the livedata as: mViewModel.getDetails().observe(getViewLifecycleOwner(), mObserver);
And tried to remove the observer as: mViewModel.getDetails().removeObservers(getViewLifecycleOwner()) or mViewModel.getDetails().removeObservers(this) or mViewModel.getDetails().removeObserver(mObserver) tried in OnViewCreated and onDestroyView and onDestory and onDetach
What is causing this and why removing the observer is not working?
FYI:
Here is the function i am using in the MainActivity to switch between fragments on navigation menu click
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
Try to set the value to null after
mViewModel.getDetails().removeObservers(getViewLifecycleOwner()).
mViewModel.getDetails().setValue(null)

Unable to update data in views in fragment

I have a view pager that returns same fragment with different data from adapter every time i swap but despite of the fact that different data is received it displaying the same data over and over again, how can i make fragment update its data
the structure is, there is a fragment that has a listview and when i click on the listview item it replaces a fragment that has viewpager and setting its adapter, the adapter is FragmentPagerAdapter and returns a fragment with argument now fragment uses its argument and display data, every time getview called of adapter returning the same fragment with different data
here is the code:
when list item clicked:
replaceFragment(ReportPaginationFragment.newInstance(i, isFromList), true, true);
ReportPaginationFragment:
viewPager.setAdapter(new ReportPaginationAdapter(getFragmentManager(), reportID, appointmentObjectArrayList, isFromList, listPosition ));
Adapter:
reportId = appointmentObjectArrayList.get(item++).getId();
return NewDrReportFragment.newInstance(reportId);
appointmentObjectArrayList is arraylist that has data
Thanks in advance
Instead of addFragment, replace is better choice.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
for (int i=0;i<categoryList.size();i++){
Category category=categoryList.get(i);
FoodFragment foodFragment = new FoodFragment();
foodFragment.setCategory(category);
pagerAdapter.addFragment(foodFragment, category.getName());
}
lets take this example. Maybe you are not setting differrent data onto pageAdapter properly.
can you share your code for more information?

Fragment doesn't update values from other fragment

I am quite new in android, my intention is to pass this values to a fragment that it is my current fragment. But I want to update the fragment, I have this data in a different fragment.
When I execute this my bundle goes to the fragment. It doesn't change even I can do setText in my textView without the app stops.
private void passToScreen(String title, String artist, String album, Long duration) {
bundle.putString("songTitle",title);
bundle.putString("songArtist", artist);
bundle.putString("songAlbum", album);
bundle.putString("durationSong", duration.toString());
mActivity.getSupportFragmentManager()
.beginTransaction()
.detach(songScreen)
.commitNowAllowingStateLoss();
songScreen.setArguments(bundle);
mActivity.getSupportFragmentManager()
.beginTransaction()
.attach(songScreen)
.commitAllowingStateLoss();
})
What am I am doing wrong?
Thank you in advance.
If the fragment is already visible, then you can get the instance of that fragment using the FragmentManager:
MyFragment myFragment = (MyFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_or_container_id);
myFragment.updateViews(bundle);
Then create the method in the fragment class to update the views:
public void updateViews(Bundle bundle) {
//update the views
}
You don't need to detach the fragment. Note that this will only work if the fragment is finished with the "commit" process. The commit() and commitAllowingStateLoss() functions work asynchronously, so if you call findFragmentById() immediately after commit(), it will return null.
Use interfaces to communicate between fragments
https://developer.android.com/training/basics/fragments/communicating.html

Completely Refresh Fragment

I have a fragment and I need to completely refresh/reinstantiate it.
By refreshing I mean recreating fragment.
I have tried using FragmentManager with detach() method but it didn't help. All EditText children of that fragment still have their values entered even though the fragment was refreshed
Is there any way to achieve this result?
if there are only edit texts , create a method that sets all edit texts to empty string that is et(edit_text object),
et.setText(""); //edit text will be reset
Put the following code inside the fragment which need to be refreshed.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
Use fragment manger according to your code (if it is an old version then this will be supportFragmentManager)
Put and call this method to your fragment
private void reloadFragment(){
Fragment frg = getActivity().getSupportFragmentManager().findFragmentByTag(ReceiptFragment.TAG);
final FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}

Categories