Passing data From Activity to Fragment using interface
<p>I want to pass data from an activity to a fragment, using an interface.
Please have a look at the code snippets below:</p>
<p>Interface:</p>
<pre><code>public interface FragmentCommunicator {

   public void passData(String name);
}
</code></pre>
<p>MainActivity:</p>
<pre><code>public class MainActivity extends AppCompatActivity{

    FragmentCommunicator fragmentCommunicator;
    private Fragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b = (Button) findViewById(R.id.button);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fragment= new Fragment();
                fragmentCommunicator = (FragmentCommunicator) getApplication();
                fragmentCommunicator.passData(&quot;hello&quot;);
                getSupportFragmentManager().beginTransaction().replace(R.id.container ,fragment).commit();

            }
        });

    }
}
</code></pre>
<p>Fragment:</p>
<pre><code>public class Fragment extends android.support.v4.app.Fragment implements FragmentCommunicator {

    FragmentCommunicator communicator;
    Context c;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, null);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.c = context;

    }
    @Override
    public void passData(String name) {
        Toast.makeText(c, name, Toast.LENGTH_SHORT).show();
    }
}
</code></pre>
<p>I just want to pass some string when I click on button, (or some other event) to launch a fragment, and when the fragment is launched, it should show a toast containing that string...</p>
<p>Please help
any help would be appreciated.</p>