Jaison Joseph Jaison Joseph - 2 years ago 90
Java Question

Not able to pass string value from one fragment to another

I know there are so many qustions regarding this , but none of them are solving my problem
I want to pass a string variable from one fragment to other, here is the code I did. but I am getting error (I will show the error)

from first fragment I did

Desc_1 ldf = new Desc_1 ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.frame, ldf).commit();


and incoming second fragment I did like

public class Desc_1 extends Fragment {

public Desc_1() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootview=inflater.inflate(R.layout.fragment_desc_1,container,false);

String value = getArguments().getString("YourKey");

Toast.makeText(getActivity(), value,
Toast.LENGTH_LONG).show();

return rootview;

}
}


I am getting error like

07-27 20:31:06.386 26816-26816/com.example.jaison.newsclient E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jaison.newsclient, PID: 26816
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at layout.Desc_1.onCreateView(Desc_1.java:34)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:725)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5769)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:861)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)

Answer Source

try this :

Bundle bundle = getArguments();
if(bundle != null)
    String value = bundle.getString("YourKey");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download