I am trying to add an ArrayList inside of another ArrayList but i always get this error :
java.lang.NullPointerException:Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
The problem seems to be the OnClickListener or the Dialog because this error does not happen in the OnCreateView(). Here is my code :
public class CoordsFragment extends Fragment {
public static ArrayList<ArrayList<String>> AllCoords = new ArrayList<ArrayList<String>>();
public FloatingActionButton fab;
public Dialog dialog;
public Button cancel;
public Button create;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_coords, container, false);
mainLayout = view.findViewById(R.id.fragment_coords_main_layout);
ArrayList<String> arr;
arr = new ArrayList<String>();
/*the 3 arr.add doesn't work because the views "name", "x" and "y" are null here but if i replace
them with normal strings it works. this is just for the exemple*/
arr.add(name.getText().toString());
arr.add(x.getText().toString());
arr.add(y.getText().toString());
//AllCords.add(arr); causes no error here
AllCoords.add(arr);
fab = view.findViewById(R.id.plus_fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fabClick();
}
});
return view;
}
public void fabClick() {
dialog = new Dialog(getActivity());
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_add_coords, null);
dialog.setContentView(dialogView);
create = dialogView.findViewById(R.id.coords_dialog_create);
create.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialogCreate();
}
});
cancel = dialogView.findViewById(R.id.coords_dialog_cancel);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialogCancel();
}
});
dialog.show();
}
public void dialogCreate() {
dialog.dismiss();
ArrayList<String> arr;
arr = new ArrayList<String>();
arr.add(name.getText().toString());
arr.add(x.getText().toString());
arr.add(y.getText().toString());
//AllCoords.add(arr); causes the error here
AllCoords.add(arr);
}
public void dialogCancel() {
dialog.dismiss();
}
}
I didn't manage to find a working solution for me. Maybe i shouldn't use an ArrayList for this code, so if you have a solution that replace the ArrayList i'm fine with it. Thank you in advance for answers and sorry in advance for my potential bad english.
Found myself where the problem was, thanks all for your answers but the problem isn't in the code i sent.
So the problem was that i was getting an ArrayList from sharedPreferences(using gson) and saving it in AllCoords. but if no data was saved in sharedPreferences, the ArrayList would always be null.
I'm sorry for wasting your time, it was impossible to find the solution with the code i sent.