Search code examples
androidandroid-dialogfragment

NullPointerException calling activity using DialogFragment


I am in the process of converting my dialogs to DialogFragments. I'm following the instructions here but it looks like they are using it in an Activity and I'm using it in a Fragment. I've created the Listener back to my fragment, but when I call getActivity() it is throwing a NullPointerException:

public class DialogTextAdd extends DialogFragment implements OnEditorActionListener {

    private EditText mText;

    public interface DialogTextAddListener {
        void onDialogTextAdd(final String inputText);
    }

    public DialogTextAdd() {
        // Empty constructor required for DialogFragment
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.dialog_edit, container);
        mText = (EditText)view.findViewById(R.id.Text_add);
        getDialog().setTitle("Add Text");

        // Show soft keyboard automatically
        mText.requestFocus();
        getDialog().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        mText.setOnEditorActionListener(this);

        return view;
    }

    @Override
    public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
        if (EditorInfo.IME_ACTION_DONE == actionId) {

            new MyFragment().onDialogTextAdd(mText.getText().toString()); //think this is my problem
            this.dismiss();
            return true;
        }
        return false;
    }
}

public class MyFragment extends SherlockListFragment implements DialogKeywordAddListener
{
    @Override
    public void onDialogTextAdd(final String text) {
        Toast.makeText(getActivity(), text + " saved", Toast.LENGTH_SHORT).show();
    }


@Override
public void onAttach(Activity act) {
    super.onAttach(act);
}


}

Using this code got it to work:

    MyFragment mf = new MyFragment();
    Bundle args = new Bundle();
    args.putString("text", mText.getText().toString());
    mf.setArguments(args);

    getActivity().getSupportFragmentManager().beginTransaction().add(mf, "my_fragment").commit();

Solution

  • Shouldn't you use getSupportFragmentManager() and add (.add(fragment, tag)) the new instance of your fragment to the FragmentTransaction by doing .beginTransaction() and then call commit()? I guess thats what you are trying to do.

    getActivity() returns null since your new Fragment instance is not attached to the Activity (native FragmentActivity/Activity or SherlockFragmentActivity/SherlockActivity, whatever it is).

    Do some readings about using fragments. Instantiantion of the fragment is not enough. Find about underlying operations after instantiation.