Search code examples
androidtextviewandroid-dialogfragmentsettextfindviewbyid

SetText of TextView in DialogFragment from Calling Activity


Building an Android app and having some trouble. I'd appreciate any help!

I have created an class that extends DialogFragment (Account_Create_Error) that I call from Activity A. I want to set the TextView field in this DialogFragment from Activity A. I created a method in my dialogfragment

public void setError(String message) {
           TextView error = (TextView)getActivity().findViewById(R.id.message);
           error.setText(message);
}

I then use this method in Activity A by doing

Account_Create_Error error = new Account_Create_Error();
error.show(getFragmentManager(), "error");
error.setError(json.getString("response"));

I seem to get a nullpointer exception from findViewById.

Please let me know if providing any more of my code would be helpful.

Thank you!!


Solution

  • We can pass data to dialog fragment using the constructor.

    UserActionDialogFragment dialog = UserActionDialogFragment.newInstance(errorMesssage);
    dialog.show(getFragmentManager(), TAG);
    

    Where UserActionDialogFragment extends DialogFragment

    public class NotificationDialogFragment extends DialogFragment {
    
        private static final String TAG = "NotificationDialogFragment";
    
        private String mMessageToDisplay;
    
        public static NotificationDialogFragment newInstance(
                String message) {
    
            NotificationDialogFragment infoDialog = new NotificationDialogFragment();
            mMessageToDisplay = message
    
    
        }
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
            alertDialog.setMessage(mMessageToDisplay);
            alertDialog.setNeutralButton(R.string.label_ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
    
                        }
                    });
            return alertDialog.create();
        }
    
    
        }