Fragment null must be a public static class to be properly recreated from instance state

拟墨画扇 提交于 2019-12-17 21:11:58

问题


I am not able to figure out why my app crashes when getSupportFragmentManager() is called.I have used similar code in other apps to create alert dialogs without any issues.please help!

DialogFragment df = new DialogFragment(){

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            View view = getActivity().getLayoutInflater().inflate(R.layout.addincome,null);
            builder.setView(view);
            //capture
            final EditText amountEditText=(EditText)view.findViewById(R.id.edit_amount);
            final EditText descriptionEditText=(EditText)view.findViewById(R.id.edit_description);
            builder.setNegativeButton(android.R.string.cancel,null);
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    newIncome.setAmount(Double.parseDouble(amountEditText.getText().toString()));
                    newIncome.setDescription(descriptionEditText.getText().toString());
                    user.incomes.add(newIncome);
                    HashMap<String,User> modified = new HashMap<>();
                    modified.put(uid,user);
                    rootref.setValue(modified);
                }
            });
            return builder.create();
        }
    };
    df.show(getSupportFragmentManager(),"addIncome");

回答1:


Your DialogFragment is an anonymous class, and in Java anonymous classes can only be instantiated by parent classes: the new DialogFragment() is in fact this.new DialogFragment(). Apparently, when FragmentManager tries to recreate your DialogFragment upon a configuration change, it can't, since it doesn't have the access to the instance of the parent class. The solution would be to either declare a static subclass of DialogFragment, or to declare a top-level subclass of DialogFragment, and use it instead of the anonymous class.




回答2:


I know you have done this step but just asking did you tried to rebuild your APK?because if this code works in other applications then their must be some .classes issue.




回答3:


check which type of Fragment you have in your imports whether your'e using android.support.v4.app.Fragment or android.os.Fragment.



来源:https://stackoverflow.com/questions/39978924/fragment-null-must-be-a-public-static-class-to-be-properly-recreated-from-instan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!