title: How can I retrieve an instance of my fragment class so I can call a method on it?
body: <p>I am learning how to use fragments, and in my MainActivity.java I have this:</p>
  
  <pre><code>@Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  
      A a = new A();
  
      B b = new B(a);
  
      if (savedInstanceState == null) {
          getSupportFragmentManager().beginTransaction()
                  .add(R.id.container, new ContentFragment())
                  .commit();
          ContentFragment frag = (ContentFragment) getSupportFragmentManager()
                  .findFragmentById(R.id.container);
          frag.doInject(b);
      }
  }
  </code></pre>
  
  <p>If I try to inject the dependency directly into the constructor of the fragment, Android Studio barks at me. So I'm trying this approach, but when debugging I get to where I am setting frag, and it's just null and is always null. So, I guess what I need to know is, in the simplest way possible, how do I call my doInject(b) and inject b into my fragment?</p>
  
  <p>Another thing too, which I'm not sure about, is that later if I have a listener in the same MainActivity.java file, and I want to update the fragment with new content, I was hoping to do something like this:</p>
  
  <pre><code>@Override
  public void handleResponseData(String s) {
      frag.updateTextbox(s);
  }
  </code></pre>
  
  <p>But I have a feeling that I'm going to run into problems with that too. So I need some help understanding what it is that I'm trying to do. I've spent at least 5 hours trying to figure this out, and need some help, please!</p>
  
  <p>Edit to show layout files:</p>
  
  <p><strong>activity_main.xml</strong></p>
  
  <pre><code>&lt;FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:id="@+id/container"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      tools:context=".MainActivity"
      tools:ignore="MergeRootFrame" /&gt;
  </code></pre>
  
  <p><strong>fragment_main.xml</strong></p>
  
  <pre><code>&lt;FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:paddingLeft="@dimen/activity_horizontal_margin"
  
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      android:paddingBottom="@dimen/activity_vertical_margin"
      tools:context=".MainActivity"&gt;
  
      &lt;TextView
          android:id="@+id/textbox"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:text="Hello World" /&gt;
  
  &lt;/FrameLayout&gt;
  </code></pre>