我正在尝试在另一个ArrayList中添加一个ArrayList,但是我总是收到此错误:
java.lang.NullPointerException:Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
问题似乎是OnClickListener或Dialog,因为在OnCreateView()中不会发生此错误。这是我的代码:
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();
}
}
我没有找到适合我的解决方案。也许我不应该为此代码使用ArrayList,所以如果您有一个替换ArrayList的解决方案,那么我很好。在此先感谢您的回答,并在此对我潜在的不良英语表示歉意。
使用它们之前,应先初始化name
,x
和y
。我没有在代码中找到变量的初始化。
发现自己在哪里,谢谢大家的回答,但问题不在我发送的代码中。
所以问题是我正在从sharedPreferences(使用gson)获取一个ArrayList并将其保存在AllCoords中。但是如果没有数据保存在sharedPreferences中,则ArrayList将始终为null。
很抱歉浪费您的时间,无法使用我发送的代码找到解决方案。