-1

Here's my code in MainActivity.java

ViewFragment fr = new ViewFragment();
Bundle bundle = new Bundle();
String val="sonali";
bundle.putString("myname", val);
fr.setArguments(bundle);
return fr;

In my ViewFragment.java the code for retrieving data in onActivityCreated() is..

Bundle bundle = getArguments();
String val = bundle.getString("myname");
if (val == null) {
   Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show();
} else {
   Toast.makeText(getActivity(), "text " + val , Toast.LENGTH_LONG).show();
} 

It gives null. Can any one help me.

Maciej Ciemięga
  • 10,125
  • 1
  • 41
  • 48

3 Answers3

0

You can also set a new instance metho for your fragment (I think it's the easiest way) and things as user name can be saved in usersettings (SharedPref).

static final ViewFragment newInstance(String myName) {
    //TODO: Save myName
}}
jobbert
  • 3,297
  • 27
  • 43
  • 1
    Check this : [You shouldn't add constructors to fragment](http://stackoverflow.com/questions/10450348/do-fragments-really-need-an-empty-constructor) – SilentKiller Sep 18 '14 at 08:40
0

a) Activity -> Fragment

In your activity : create a bundle and use

     fragment.setArguments(bundle)

in your fragment : use

     Bundle bundle = getArguments()

2) fragment -> Activity

In your fragment : create un interface with getter and setter methods (callback methods) In your activity : implement the interface 3) fragment -> Activity

In your activity : Create public getter and setter or other methods In your fragment : called public activity getter, setter or other methods using :

    getActivity().getSomething(), getActivity().setSomething(args) or getActivity().someMethod(args)

4) activity -> fragment

In your fragment : create a public method

In your activity : call an active fragment public method :

    getSupportFragmentManager().findFragmentById(R.id.your_fragment).publicMethod(args)
0

I tried it & it works fine. In activity onCreate method add

Bundle bundle = new Bundle();
    bundle.putString("my_key","my_value");
    ViewFragment fg = new ViewFragment();
    fg.setArguments(bundle);
    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, fg)
                .commit();
    }

In fragment on onActivityCreated add

Bundle bundle = getArguments();
        String value = bundle.getString("my_key");
        Toast.makeText(getActivity(),value,Toast.LENGTH_SHORT).show();
Sayem
  • 4,891
  • 3
  • 28
  • 43
  • I add this code but it says."The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, ViewFragment)".can you pls help. – Sonali Patil Sep 18 '14 at 09:49