Setting fragments by tag - android

How do I go about setting my Fragments by tag since I did not explicitly make them in my XML so I can't use findbyID.
I have 4 Fragments in an Activity and want to pass data back and forth from the Fragments but I keep getting error
Attempt to invoke virtual method 'void
com.project.myproject.app.Fragment.addToList()' on a null object
reference
I don't think I am setting my Fragment's tags right so could someone please link me to an example of this?

Set the tag for fragment:
YourFragment fragment = getFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, fragment, "YOUR_TAG").addToBackStack("YOUR_TAG").commit();
Get the fragment:
private YourFragment getFragment() {
YourFragment fragment = getSupportFragmentManager().findFragmentByTag("YOUR_TAG");
if (fragment == null) {
fragment = new YourFragment();
}
return fragment;
}

Related

How should i call viewpager instance in activity?

My ViewPager is located in nested fragment, because i also have navigation drawer. My question is how can i call instance of viewpager in MainActivity.java, so i can set current item of viewpager using method setCurrentItem() from MainActivity.java in method onBackPressed(), when for example user is on third fragment of viewpager and when he presses back button he should be returned on first fragment.
First, you have to declare RecyclerView as public. Not sure if it has to be static, but it'll tell you if it has to.
Second, you need to call an instance of the fragment that holds the RecyclerView.
For example, Fragment recyclerFrag = new RecyclerFrag();
After that, try calling your RecyclerView from that instance and use setCurrentItem(). For example, recyclerFrag.recyclerView.setCurrentItem(0).
I have found a solution. You should first create one method in FragmentActivity where is initialized your ViewPager and set return type ViewPager. Something like this:
public ViewPager getViewPager() {
return mViewPager; // instance of view pager
}
After that create object of your Fragment in Activity where you are calling instance of view pager like this:
YourFragment fragment = new YourFragment();
And in my case i should call viewpager in onBackPressed():
HomeFragment fragment1 = new HomeFragment();
if (fragment1.getViewPager().getCurrentItem() == 1 || fragment1.getViewPager().getCurrentItem() == 2) {
fragment1.getViewPager().setCurrentItem(0);
} else {
super.onBackPressed();
}

GetTag of Fragment returns the null object reference

Using an application in which the multiple Fragments are in used and
following code to fetch selected position of the fragment.
private BaseFragment getSelectedFragment(FragmentManager fragmentManager)
{
int item = getModel().getSelectedItem();//0th position last
String tag = String.valueOf(item);
BaseFragment fragment = (BaseFragment) fragmentManager.findFragmentByTag(tag); //error shown at this line
return fragment;
}
and calling above method from
public boolean onBackPressed()
{
FragmentManager fragmentManager = activity.getFragmentManager();
BaseController fragmentController = getSelectedFragment(fragmentManager).getController();
}
and crashed due to following errors
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String xxx.android.fwk.app.fragment.BaseFragment.getTag()' on a null object refrence.
replacing a fragment by using following code
private void displaySelectedFragment()
{
FragmentManager fragmentManager = getFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0) {
// pop any inner fragments that have been added.
fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
// get the selected item position
int selectedItem = model.getSelectedDrawerItem().getItemId();
String tag = String.valueOf(selectedItem);
Bundle extras = model.getExtras();
BaseFragment newFragment = NomadFragmentManager.getInstance().getFragment(selectedItem, extras);
if (newFragment != null) {
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.replace(R.id.container, newFragment, tag);
ft.commit();
}
}
so what's the actual problem cause ? digging into this code.
Any help much appriciated.
Thanks in advance
Quoting from Document
Replace an existing fragment that was added to a container. This is
essentially the same as calling remove(Fragment) for all currently
added fragments that were added with the same containerViewId and then
add(int, Fragment, String) with the same arguments given here.
Replacing a Fragment will completely remove it from back stack. So, in case you are trying to retrieve the Tag after transaction to other Fragment then it will not be available. You should add the Fragments to back stack using
addToBackStack(tagName).
From your crash log,it seems this is not the line number where you are getting the crash. The crash is due to the call of getTag() from a null fragment. Maybe after this method returns null and then you are using that fragment instance which gives null pointer exception.
BaseFragment fragment = (BaseFragment) fragmentManager.findFragmentByTag(tag);
if(fragment != null){
return fragment.
}
return null;
Maybe putting debug point at fragment != null might clarify your issue.
UPDATE
After your code update,you should not get any null pointer further. but you should put a log to check wheather it becomes null or not.
For above problem, as described above the Fragment is coming as null.
So,
BaseFragment frag = getSelectedFragment(fragmentManager);
if(frag == null) return true;
BaseController fragmentController = frag.getController();
Resolved the issue by putting check of null reference.

IllegalStateException:Fragment already active

I have a passed data from FragmentActivity to multiple fragments like this
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("userid", logindata);
firstfragment.setArguments(bundle);
From fragment Activity to secong fragment i have pass data like this.
secondfragment.setArguments(bundle);
when i click first fragment it's working next click second fragment it's also working fine but again click first fragment the illegal state exception Fragment already active exception will be occur. How to reslove this problem please help me. Thanks in advance.
illegal state exception Fragment already active
setArguments only called before the fragment has been attached to its activity otherwise through Fragment already active Exception. so call setArguments to should need to remove fragment is already present and use replace to add fragment again.
Remove fragment before adding new :
Fragment fragment =
getSupportFragmentManager().findFragmentByTag("firstfragment");
if(fragment != null)
getSupportFragmentManager().beginTransaction()
.remove(fragment).commit();
Now add new fragment :
firstfragment.setArguments(bundle);
transactn = mngr.beginTransaction();
transactn.replace(R.id.content_frag,firstfragment).
addToBackStack("firstfragment").commit();
Try this:
createFragment(new YourFragment());
private void createFragment(Fragment fragment) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container_app, fragment).commit();
}

Android : Textview giving null pointer exception in fragment

I am having a fragment A in which i initialized another fragment say Frgament B. My fragment A is having a listview. On click of that listview i need to call a method of fragment B and update Textview. But as soon as i call this method it flashes following message in Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
My code is as follows :
public class FragmentA extends Fragment {
// in oncreateview
FragmentB fb=new FragmentB();
// on listview click item i call a method of fragment B
setdata(value); // where value is clicked position
}
// Fragment B is as follows :
public class FragmentB extends Fragment {
// IN ONCRAETEVIEW
initialized textview
return view;
public void setdata(int data)
{
// Updating textview settext method
}
}
Please help
Thanks in advance
Only the fragment B is add into the layout then the View of the fragment B is created. So you should call setdata() after the fragment transaction.
Fragment fragmentB = new Fragment();
getFragmentManager().beginTransaction().add(R.layout.container, fragmentB).commit();
fragmentB.setData(value);
FragmentManager m=getSupportFragmentManager();
FragmentB fb=(FragmentB )m.findFragmentById(R.id.your_fragment_id_from_xmlsetdata);
fb.setdata(value);
try with this code it will definitely works

getParentFragment returning null

I have a Fragment that has a FrameLayout. This first fragment (A) loads inside its Framelayout another fragment (B). When I call getParentFragment from inner fragment (B), I get null. How should this method be used properly?
getParentFragment() was introduced in API level 17 (Android 4.2). Android 4.2 introduced the idea of nested fragments (fragments containing other fragments). Calling this results in null if the fragment has a parent which is an Activity.
Have a look at this.
If you are using support library then you can use getParent(), may be you need to use getChildFragmentManager() while doing fragment transaction.
See this
In my case, although my fragmentA was nested in fragmentB,but I still get null after call getParentFragment in FragmentA. Finally I found that I should use getChildFragmentManager rather than getFragmentManager in FragmentB.
check this What is difference between getSupportFragmentManager() and getChildFragmentManager()?
The one thing that helped is, when creating adapter use getChildFragmentManager().
If you are not using adapter, just use getChildFragmentManager() when doing transactions.
setTargetFragment() is not recommended, since it gives errors on moveState() of fragment(because fragments should be tied to FragmentManager)
I faced the same issue , and fixed the issues by hosting second fragment in your parent fragment with getChildFragmentManager() then you wont be getting the null value ...
Parent fragment
SignUpFragment signUpFragment = new SignUpFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.contentPanel, signUpFragment)
.addToBackStack(null).commit();
Child fragment : what i have used is a dialog
HospitalCardDialog hospitalCardDialog = new HospitalCardDialog();
hospitalCardDialog.show(getChildFragmentManager(), "");
Just in case someone using viewpager inside fragment and facing same issue.
Like if you want parent viewmodel using getParentFragment() inside child fragment. You need to use constructor with fragment not with fragmentActivity
Do not use this
public PagerAdapter(#NonNull FragmentActivity fragmentActivity, Bundle arguments) {
super(fragmentActivity);
this.arguments = arguments;
}
But use this
private static class PagerAdapter extends FragmentStateAdapter {
private final Bundle arguments;
public PagerAdapter(#NonNull Fragment fragment, Bundle arguments) {
super(fragment);
this.arguments = arguments;
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 1:
return MeterPhotoUploadFragment.newInstance(arguments);
default:
return ServiceConnectionDetailsFragment.newInstance(arguments);
}
}
#Override
public int getItemCount() {
return 2;
}
}
Usage:
PagerAdapter pagerAdapter = new PagerAdapter(this, getArguments());

Categories

Resources