There are 2 fragments: A and B. From fragment A i want to send ArrayList (data) to fragment B.
action() - a method in which data transfer and transition to fragment B should occur (using navigate()). The program builds without errors, but when you click on the button to which the action method is attached, a crash occurs, the error is as follows:
java.lang.IllegalArgumentException: Wrong argument type for 'array' in argument bundle. java.util.ArrayList expected.
It says that I inserted an argument of the wrong type into the Bundle, an ArrayList is needed. But it is an ArrayList, isn't it?
Please help, i've been struggling with this problem for 2 days now. My code is below.
Fragment A code:
package com.github.dev.app.pack;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.navigation.fragment.NavHostFragment;
import com.github.vladosspasi.mes.databinding.FragmentABinding;
import java.util.ArrayList;
public class FragmentA extends Fragment {
private FragmentABinding binding;
private ArrayList<Integer> data; // ArrayList that i want to send
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentAsBinding.inflate(inflater, container, false);
return binding.getRoot();
}
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
data = new ArrayList<>();
data.add(1);
binding.actionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
action(); //method with navigating to fragmentB and data transmitting
}
});
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
private void action() {
Bundle arg = new Bundle();
arg.putSerializable("array", data); //putIntegerArrayList doesn't work either
NavHostFragment.findNavController(FragmentA.this)
.navigate(R.id.action_FragmentA_to_FragmentB, arg); //exception ocuring here
}
}
Fragments declaration in nav_graph.xml:
<fragment
android:id="@ id/FragmentA"
android:name="com.github.dev.app.pack.FragmentA"
android:label="Fragment A">
<action
android:id="@ id/action_FragmentA_to_FragmentB"
app:destination="@id/FragmentB"/>
</fragment>
<fragment
android:id="@ id/FragmentB"
android:name="com.github.dev.app.pack.FragmentB"
android:label="Fragment B">
<argument android:name="array" app:argType="java.util.ArrayList"/>
</fragment>
int, String and other arguments are working properly, but ArrayList isn't. Please help! Thank you.
CodePudding user response:
Please use below code to send the data from one fragment to another fragment
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("array",data);