6

I'm trying to send data from an activity to a fragment. I'm not sending data from a fragment to an activity. I've got everything set up correctly other than instantiating the interface listener object in the activity.

public class Activity extends AppCompatActivity {

  private FragmentInterface fragmentInterfaceListener;

  @Override 
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // This line below is actually in a button onClick()
    fragmentInterfaceListener.sendDataMethod(dataToSend);

  }

  public interface FragmentInterface {
    void sendDataMethod(SampleData sampleData);
    }
  }

Then in the fragment, I have:

public static class CustomFragment extends Fragment implements Activity.FragmentInterface {

  @Override
  public void sendDataMethod(final SampleData sampleData) {

  }    
}

When I put a log line in the button onClick(), the log line appears when the button is clicked. No, I'm not going to put the sampleData in a fragment bundle. Yes, I need to send the data through an interface. So how do I correctly instantiate the fragmentInterfaceListener object in the Activity? Am I missing anything else in the Activity or CustomFragment?

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
langsmith
  • 2,529
  • 1
  • 11
  • 13
  • You have to ask clearly. Dont be lazy to put your code – zihadrizkyef Oct 05 '17 at 01:18
  • 1
    Instead of you keep `FragmentInterface` interface in your activity why don't you keep `CustomFragment` fragment in your activity for instead. And then you can declare public methods in the `CustomFragment` fragment so that your activity can use these methods easily. – John Le Oct 05 '17 at 02:49

3 Answers3

13

What your are missing here is the registering part.

The fragment has to register itself with the activity listener for the activity to send data when an event occurs.To do this create a method in activity

private void setOnDataListener(FragmentInterface interface){
    fragmentInterfaceListener=interface;
}

And in the oncreate of your fragment set the listener like this

((YOUR_ACTIVITY_NAME)getActivity()).setOnDataListener(this);
Sharath kumar
  • 4,064
  • 1
  • 14
  • 20
  • i did same way but go "NullPointerException: Attempt to invoke interface method 'void com.example.appname.Interfaces " in my activity class – Adnan haider Apr 10 '21 at 09:03
3

You don't need to use listener in the Fragment because you can directly communicate with the Fragment from its host Activity.

As @lq-gioan says, you can create a public method in your Fragment then call it from your activity. So, create a public method to set the data, something like this:

public static class CustomFragment extends Fragment {

  // public method to be accessed by host activity.
  public void sendDataMethod(final SampleData sampleData) {

  }    
}

Then you can call the method within your host activity:

CustomFragment fragment = (CustomFragment)getSupportFragmentManager()
                           .findFragmentById(R.id.fragment_id);

// or use find by tag if you adding the fragment by tag
// CustomFragment fragment = (CustomFragment)getSupportFragmentManager()
//                           .findFragmentByTag("FragmentTag");

// now you can call it
fragment.sendDataMethod(yourSampleData);
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
  • Can I just save reference to my fragment in host activity and then just call it's method? Not to findFragmentById each time. – yozhik Apr 25 '18 at 10:47
  • 1
    Of course, you can save all your fragment references to a list then use it to call the method. But you need to make sure you're not calling the nulled fragment. – ישו אוהב אותך Apr 25 '18 at 13:23
  • Thanks! And maby you have faced the same issue as this guy did? https://stackoverflow.com/questions/20355127/android-lifecycle-management-of-fragments-within-viewpager-and-fragmentpageradap If yes - how did you fixed it, because the accepted answer is not looks like valid. – yozhik Apr 25 '18 at 14:22
  • 1
    I'm using `SmartFragmentStatePagerAdapter` from this https://guides.codepath.com/android/viewpager-with-fragmentpageradapter. It will solve the issue for fragment management of view pager. – ישו אוהב אותך Apr 25 '18 at 14:29
1

For sending data from Activity to Fragment we don't need an interface.

You can directly call the method in Fragment or pass as setArguments in Bundle

     ArticleFragment articleFrag = (ArticleFragment)
            getSupportFragmentManager().findFragmentById(R.id.article_fragment);

    if (articleFrag != null) {
        // If article frag is available, we're in two-pane layout...

        // Call a method in the ArticleFragment to update its content
        articleFrag.updateArticleView(position);
    } else {
        // Otherwise, we're in the one-pane layout and must swap frags...

        // Create fragment and give it an argument for the selected article
        ArticleFragment newFragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putInt(ArticleFragment.ARG_POSITION, position);
        newFragment.setArguments(args);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }

You can refer https://developer.android.com/training/basics/fragments/communicating.html

Yatish
  • 521
  • 3
  • 14