Run function in another fragment - android

I want to run a function from main activity, but function is another fragment. This is my code
FragmentManager fm = getSupportFragmentManager();
ConversationFragment fragment = (ConversationFragment)fm.findFragmentById(R.id.container);
fragment.addMessageToList("ok");
I placed this code to onCreate in MainActivity, and this is the addMessageToList function in fragment:
public void addMessageToList(String message) {
Log.w("Step 2",message);
}
But my app is crashing. Here logcat:
How can I fix it ?

You were using findFragmentById() when you had no fragment with that id on your Activity layout. When replacing a fragment in your container, add a tag to it. Like this:
fragmentTransaction.replace(R.id.container, frgObj,"ConversationFragment");
Then, use findFragmentByTag("ConversationFragment") to have your Fragment and execute methods with it.

Related

Start Fragment via function in MainActivity

I'm trying to start a fragment programmatically. The function below works fine on its own. The problem here is, that I have to call the function from within another fragment. The call from the fragment to MainActivity works and is not the problem.
public void gotoFragment1(){
Fragment1 fragment = new Fragment1();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
If I try to call the function from another fragment the app crashes with the following stacktrace:
java.lang.IllegalStateException: FragmentManager has not been attached to a host.
at androidx.fragment.app.FragmentManager.enqueueAction(FragmentManager.java:1727)
at androidx.fragment.app.BackStackRecord.commitInternal(BackStackRecord.java:321)
at androidx.fragment.app.BackStackRecord.commit(BackStackRecord.java:286)
at com.fewo.info.MainActivity.gotoVeranstaltungen(MainActivity.java:134)
at com.fewo.info.ui.home.HomeFragment$1.onClick(HomeFragment.java:53)
How can I change the fragment with this code beeing called from within another fragment?
if you want replace a fragment in MainActivity from other Fragments, you can do it in your fragment (No need to call function from MainActivity),
use this in your fragment:
getFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment, new Fragment1(), FragmentLoanList.class.getName()).addToBackStack(null)
.commit();
Fragment A:
((ActivityOne) getActivity()).callFragmentB();
Activity One
public void callFragmentB(){
//run your fragment transaction To B here
}

call fragment method but fragment not prepared complitily

I want to dynamically create fragment. So when click the navigation fragment item, it will trigger the callback function in the activity to communicate with detail fragment. Here is the callback faction in activity:
public void getChatRoomId(long chatroom_id) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
MsgChatRoom msgChatRoom = new MsgChatRoom();
ft.replace(R.id.activity_chat_MsgChatroom_container, msgChatRoom, "messages");
ft.addToBackStack(null);
ft.commit();
msgChatRoom.startQuery(chatroom_id);
}
I could call the startQuery method, but in that method I need some arguments should be initialize in onCreateActivity(). However, at the time when I call startQuery, the Fragment does not have called OncreateActivity. So there will be a error:
.... on a null object reference
How to solve this problem. Thanks in advance.
You can pass arguments to the fragment by using Fragment's setArguments(Bundle) function.
When you create the fragment pass your arguments by setArguments() and then in your fragment retrieve them by calling getArguments() in this way you don't wait for specific fragment's life-cycle to be able to use your data.
For more information you can visit http://developer.android.com/reference/android/app/Fragment.html which also contains couple of examples of using these functions

Alternative of findFragmentById for getting a reference of already open fragment

Im trying to tell a fragment to change a certain view's visibility from the activity, but I dont know how to get a reference to that fragment.
What I found is
findFragmentById(R.id.asdasd)
But my fragment is not inflated from an XML layout so it doesnt have such an ID (I guess?)
So how can I reference this fragment in another way?
Here is how I add the fragment from the activity:
public void addFragment(Fragment fragment) {
String fragmentClassName = ((Object) fragment).getClass().getSimpleName();
FragmentTransaction t = getFragmentManager().beginTransaction();
t.replace(R.id.fragment_container, fragment, fragmentClassName);
t.addToBackStack(fragmentClassName);
t.commit();
Since you already set the tag in your fragment you can use it to find the fragment by its tag using the Fragment Manager.
sample:
String fragmentClassName = The_Class_Name_Of_Fragment.getClass().getSimpleName();
YourFragment fragment = getFragmentManager().findFragmentByTag(fragmentClassName);
You should call findFragmentById(R.id.fragment_container) to reference your Fragment.

GetFragmentManager.findFragmentByTag() returns null

getFragmentManager().beginTransaction()
.replace(R.id.graph_fragment_holder, new GraphFragment(), "GRAPH_FRAGMENT")
.commit();
getFragmentManager().beginTransaction()
.replace(R.id.list_fragment_holder, new ListFragment(), "LIST_FRAGMENT")
.commit();
//getFragmentManager().executePendingTransactions();
GraphFragment graphFragment = (GraphFragment) getFragmentManager().findFragmentByTag("GRAPH_FRAGMENT");
graphFragment.setData(data);
ListFragment listFragment = (ListFragment) getFragmentManager().findFragmentByTag("LIST_FRAGMENT");
listFragment.setData(data);
I've supplied a tag so I'm not sure why findFragmentByTag() returns null.
What I've tried from reading other questions:
this.setRetainInstance(true) in the oncreate of both fragments.
Both fragment constructors are empty public fragmentName(){}.
tried executePendingTransactions after adding the fragments.
tried add instead of replace on the fragments (edited)
I was confused about this for a long time. First, you need to save the fragment you are replacing by pushing it onto the back stack. The tag you supply is put on the fragment you are adding, not the one you are pushing onto the back stack. Later, when you do push it onto the back stack, that tag goes with it. Here's code with objects broken out to make it easier to trace. You must call 'addToBackStack' before 'commit'.
GraphFragment grFrag = new GraphFragment();
FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
tr.replace(R.id.fragment_container, grFrag, "GRAPH_FRAGMENT");
// grFrag is about to become the current fragment, with the tag "GRAPH_FRAGMENT"
tr.addToBackStack(null);
// 'addToBackStack' also takes a string, which can be null, but this is not the tag
tr.commit();
// any previous fragment has now been pushed to the back stack, with it's tag
ListFragment liFrag = new ListFragment();
FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
tr.replace(R.id.fragment_container, liFrag, "LIST_FRAGMENT");
// liFrag is is about to become the current fragment, with the tag "LIST_FRAGMENT"
tr.addToBackStack(null);
tr.commit();
// 'grFrag' has now been pushed to the back stack, with it's tag being "GRAPH_FRAGMENT"
Call getFragmentManager().executePendingTransactions() after fragment transaction.
getFragmentManager()
.beginTransaction()
.replace(R.id.container, new ExampleFragment(), "YOUR TAG HERE");
.commit();
//after transaction you must call the executePendingTransaction
getFragmentManager().executePendingTransactions();
//now you can get fragment which is added with tag
ExampleFragment exampleFragment = getFragmentManager().findFragmentByTag("YOUR TAG HERE");
I was having the same problem of findFragmentByTag() always returning null.
Eventually I tracked it down, I was overriding onSaveInstanceState() in my Activity but not calling super. As soon as I fixed that findFragmentByTag() returned the Fragment as expected.
You can use
fragmentTransaction.addToBackStack(yourFragmentTag);
After that you can reuse it with
getSupportFragmentManager().findFragmentByTag(yourFragmentTag);
Answered here, just need to call getSupportFragmentManager().executePendingTransactions(); after your findByTag or findById
In my case I had to create a class level FragmentManager object and then use it instead of using getSupportFragmentManager() directly.
public class Main extends BaseActivity {
FragmentManager fragmentManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragmain);
fragmentManager = getSupportFragmentManager();
initFrag1();
}
private void initFrag1() {
String name = Frag1.class.getSimpleName();
if (fragmentManager.findFragmentByTag(name) == null) {
fragmentManager.beginTransaction()
.add(R.id.frag_container, new Frag1(), name)
.addToBackStack(name)
.commit();
}
}
}

Changing Fragments inside Activity through onListItemClick()

I have this Activity which at first shows a Fragment with a list of elements. This works perfectly with this code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_act);
if(null == savedInstanceState)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ListFragment glfragment = new ListFragment();
fragmentTransaction.add(R.id.listfrag1, glfragment);
fragmentTransaction.commit();
}
}
Well I have a ListFragment and a DetailFragment. But I don't know how to do the transition when I click an element of the list. I know the fragmentTransaction.replace(), but I don't know WHEN to call it.
I thought I should use the OnListItemClick() inside the ListFragment, but I don't know how to use the FragmentManager inside the Fragment and not in the main Activity... Also I want to "export" some data to the DetailFragment as if it was a Intent, but it's not.
To use the fragment manager inside your Fragment, simply call
getActivity().getFragmentManager() instead of getFragmentManager(). Implementing this in your OnItemClickListener should suffice.
What I would do is:
Define an interface with one method listItemSelected() with as an argument the id of the selected item
Let your activity implement this interface
In the onAttach of your list fragment, take the activity and keep it as a member variable, cast to the interface type. Make sure that in the onDetach you dereference it.
In your onListItemClick, call this method on your activity
In the activity, you can now do a new fragmenttransaction, this time you need to replace instead of add the fragment
To create your detail fragment with the correct argument (the id), use the method described here.
This should normally work fine.

Categories

Resources