Search code examples
javaandroidandroid-fragmentactivityandroid-safe-args

Problem with passing data between fragments with SafeArgs


I want to pass a string from one fragment to another. The problem is that my HomeFragmentDirections class says that an action I want to get "has private access".

Nav_graph.xml:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/nav_home">

<fragment
    android:id="@+id/nav_home"
    android:name="com.example.chronosaur.ui.HomeFragment"
    android:label="Home"
    tools:layout="@layout/fragment_home">
    <action
        android:id="@+id/action_add_data"
        app:destination="@+id/addDataFragment" />
</fragment>
<fragment
    android:id="@+id/nav_diagram"
    android:name="com.example.chronosaur.ui.DiagramsFragment"
    android:label="fragment_diagrams"
    tools:layout="@layout/fragment_diagrams" />
<fragment
    android:id="@+id/nav_shop"
    android:name="com.example.chronosaur.ui.ShopFragment"
    android:label="fragment_shop"
    tools:layout="@layout/fragment_shop"/>
<fragment
    android:id="@+id/addDataFragment"
    android:name="com.example.chronosaur.ui.AddDataFragment"
    android:label="Add data"
    tools:layout="@layout/fragment_add_data" >
    <argument
        android:name="currentDate"
        app:argType="string"
        android:defaultValue="default" />
</fragment>

HomeFragment:

 String currentDate = "hello";
 @Override
 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
 super.onActivityCreated(savedInstanceState);

 btn_add = getActivity().findViewById(R.id.btn_add);
 btn_add.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        HomeFragmentDirections.ActionAddData() action = new HomeFragmentDirections.ActionAddData(); 
     // error in this string
        action.setCurrentDate(currentDate);
        Navigation.findNavController(v).navigate(action);

      }
    });
   }

Error, it doesn't let me to start the app:

error: ActionAddData() has private access in ActionAddData

How can I solve the problem? Thanks for any help.


Solution

  • Pass the String value direct to the constructor like:

    HomeFragmentDirections.ActionAddData() action = new HomeFragmentDirections.ActionAddData("Your String Value");