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
  • 90,984
  • 81
  • 374
  • 818
Tolgay Toklar
  • 3,732
  • 8
  • 38
  • 63

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,754
  • 5
  • 26
  • 41