ahmed sharief
ahmed sharief

Reputation: 83

How to pass string from one fragment to another in android

I have two fragments and i want to send fragment2 string to fragment1 and store it in a string in fragment1. When i try to do this in a normal way it shows me a error which i have posted down. Someone please help me.

Fragment2.class

Bundle bundle=new Bundle();
bundle.putString("message", value);//value= my value from code
Fragmentclass2 frag2=new Fragmentclass2();
frag2.setArguments(bundle);

Fragment1.class

 final String store= getArguments().getString("message");

Error log:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

Upvotes: 1

Views: 1538

Answers (2)

Anshul Nema
Anshul Nema

Reputation: 319

I recommend to use this way

when you pass the data from first fragment

val bundle = Bundle()
bundle.putString(Constants.ROOM," room")

val fragment= GroupRoomDevicesFragment()
fragment.arguments=bundle
getChildFragmentManager().beginTransaction()
            .replace(R.id.fl_automate, fragment)
            .addToBackStack("name")
            .commit()

when you get the data from another fragment

var screentext=requireArguments().getString(Constants.ROOM)

Upvotes: 2

João Zão
João Zão

Reputation: 180

I recommend you to use the newInstance() fragment general practice.

For that you should consider to create the newInstance() method in your Fragmentclass1like this:

public static Fragmentclass1 newInstance(String value) {
    Fragmentclass1 fragmentclass1 = new Fragmentclass1();

    Bundle args = new Bundle();
    args.putString("message", value);
    fragmentclass1.setArguments(args);

    return fragmentclass1;
}

In your Fragmentclass2 you call:

Fragmentclass1.newInstance("YOUR_MESSAGE")

this will create the Fragmentclass1 so the last thing to do is to retrieve the arguments in the onCreate of the Fragmentclass1. Like you were doing:

final String store= getArguments().getString("message");

Upvotes: 0

Related Questions