0

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:

enter image description here

How can I fix it ?

jww
  • 97,681
  • 90
  • 411
  • 885
Tolgay Toklar
  • 4,151
  • 8
  • 43
  • 73

1 Answers1

0

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.

joao2fast4u
  • 6,868
  • 5
  • 28
  • 42