Search code examples
javaandroidandroid-dialogfragment

Cant set text to EditText in DialogFragment


I have a button in listview row that when I click on it I want a dialogFragment to be open and set the text of an edit text (that located inside the dialogFragment) to some String.

The problem is: the app shut down when it comes to the line of the settext method.

This is the code I use to open the dialogFragment and set text to it.

public void onClick(View v) {
    FragmentManager manager = getFragmentManager();
    View parentRow = (View) v.getParent();
    ListView listView = (ListView) parentRow.getParent();
    final int position = listView.getPositionForView(parentRow);
    TrempData data = adapter.getItem(position); //from here im getting the data that i want to set to the edit text. 
    Addtremp trempDialog = new Addtremp();
    trempDialog.show(manager, "Addtremp");
    trempDialog.from.setText(data.get_from());
    trempDialog.to.setText(data.get_to());
    trempDialog.date.setText(data.get_date());
    trempDialog.time.setText(data.get_time());
    trempDialog.extra.setText(data.get_extras());
}

Hope someone could help me.

Thanks.


Solution

  • Your App will surely crash due to NullPointerException. Because you are trying to set data on UI which is not rendered yet.

    What steps should follow?

    1. Pass data to DialogFragment which is going to display on UI in a form of arguments.

    2. Create callback which will inform you when UI is rendered on Dialog. Check this Callback to a Fragment from a DialogFragment . On getting listener you could set data on your UI components.

    Personally I prefer solution1 and for that you should read passing argument to DialogFragment