Lớp của tôi phải chuyển đối số cho DialogFragment, nhưng ứng dụng của tôi bị treo bên trong phương thức onCreate (của lớp thoại) cho một NullPointerException. Dialog phần lớp đoạn mã:Đối số DialogFragment và nullpointer ngoại lệ
public class ConfirmDialog extends DialogFragment {
public ConfirmDialog() {}
ConfirmDialog newInstance(String f) {
ConfirmDialog d = new ConfirmDialog();
Bundle args = new Bundle();
args.putString("FILE_NAME", f);
d.setArguments(args);
return d;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
file = getArguments().getString("FILE_NAME");
}
Tôi có nullpointer tại dòng này:
file = getArguments().getString("FILE_NAME");
Và tôi không biết tại sao. tôi dán cũng mã gọi thoại
private void showConfirmDialog(String file) {
FragmentManager fm = getSupportFragmentManager();
ConfirmDialog dialog = new ConfirmDialog();
Log.i("SHOWFILEACTIVITY", file);
dialog.newInstance(file);
dialog.show(fm, "fragment_confirm_dialog");
}
Ở đây, "tập tin" chuỗi không phải là null, tôi đã kiểm tra nó với
Log.i("SHOWFILEACTIVITY", file);
ok cảm ơn, nó hoạt động. Tôi chưa bao giờ sử dụng chức năng newInstance và tôi đã phạm sai lầm! nhưng tại sao newInstance phải tĩnh? – giozh
@giozh vì chúng ta muốn tạo một thể hiện 'mới' của Hộp thoại, đó là một phương pháp thiết kế xấu dựa vào một thể hiện * đã được tạo ra của Hộp thoại. Việc giữ phương thức tĩnh loại bỏ các phụ thuộc và kết quả trong việc tạo đối tượng ít hơn. –