user3745498
user3745498

Reputation: 23

How to pass value from activity to fragment in android

How can I get a value(String) from activity and then use it in Fragment? errors are occurred

fragment.java

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");
    View rootView = inflater.inflate(R.layout.fragment_user_info,
            container, false);

    return rootView;
}

activity.java

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
UserInfoFragment fragobj = new UserInfoFragment();
fragobj.setArguments(bundle);

Upvotes: 2

Views: 85

Answers (2)

Eugen Pechanec
Eugen Pechanec

Reputation: 38223

The error is a NullPointerException, correct?

This is because you read the arguments (in the fragment's constructor):

String strtext = getArguments().getString("edttext");

before you assign them (in activity after the fragment's constructor has already been called):

fragobj.setArguments(bundle);

Keep the constructor simple. Best solution is to create a static factory method newInstance(String edttext) according to this guide https://stackoverflow.com/a/9245510/2444099 like so:

public static UserInfoFragment newInstance(String edttext) {
    UserInfoFragment myFragment = new UserInfoFragment();

    Bundle args = new Bundle();
    args.putInt("edttext", edttext);
    myFragment.setArguments(args);

    return myFragment;
}

Then use this factory method instead of constructor whenever you need to obtain a new fragment instance.

Upvotes: 1

Andrew Schuster
Andrew Schuster

Reputation: 3229

This is what's happening in your current code:

  1. You create the Fragment

  2. In the onCreateView() method, you get the arguments

  3. You set the arguments in your Activity.

In other words, you're calling the arguments before you've set them. As per the Fragment Documentation, you should be using a static method to instantiate your Fragments. It would look something like the following.

In your Fragment class, add this code

/**
 * Create a new instance of UserInfoFragment, initialized to
 * show the text in str.
 */
public static MyFragment newInstance(String str) {
    MyFragment f = new MyFragment();

    // Supply index input as an argument.
    Bundle args = new Bundle();
    args.putString("edttext", str);
    f.setArguments(args);

    return f;
}

And now, in your Activity, do the following:

//Bundle bundle = new Bundle();
//bundle.putString("edttext", "From Activity");
//UserInfoFragment fragobj = new UserInfoFragment();
//fragobj.setArguments(bundle);

UserInfoFragment fragobj = UserInfoFragment.newInstance("From Activity");

Notice how now, you don't even need to create a Bundle and set it in your Activity class, it is handled by the static newInstance() method.

Upvotes: 1

Related Questions