user2737686 user2737686 - 1 year ago 104
Android Question

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(;

I then use this method in Activity A by doing

Account_Create_Error error = new Account_Create_Error();, "error");

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!!

Answer Source

We can pass data to dialog fragment using constructor. UserActionDialogFragment dialog = UserActionDialogFragment.newInstance(errorMesssage);, 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


public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {

    return alertDialog.create();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download