java - 无法从 onClickListener 添加到 arraylist
问题描述
我正在尝试在另一个 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
我没有在代码中找到变量的初始化。
推荐阅读
- haskell - 在haskell中自动解包/重新包装值的功能?
- python - 解压缩大文件 - Google Colab Notebook
- image - PDF 和 Word 提取覆盖在图像上的文本
- c# - 如果计算机上使用 DateTime.UtcNow 的日期错误,则日期错误
- python - 转换为列表理解
- java - Hibernate: Criteria & createSQLQuery: 如何得到正确的 JSON?
- pandas - 如何通过匹配熊猫数据框中的字符串来使用索引
- javascript - 如何在数据更新后重新加载图表?
- mysql - 如何根据从 Angular 数据库中获取的 URL 显示特定页面?
- python - 有关 a=b=c 工作原理的详细信息