Как получить значение нашего пользовательского AlertDialog? - PullRequest
0 голосов
/ 04 марта 2020

Я создал пользовательский AlertDialog и хочу сохранить значения, заданные пользователем. Однако я не могу получить к ним доступ, потому что Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference.

Я нахожусь в HomeFragment, я создал AlertDialog и установил макет. Я сделал это так:

  public class HomeFragment extends Fragment implements CustomDialog.CustomDialogListener {

    private HomeViewModel homeViewModel;
    private View root;

    public View onCreateView(@NonNull final LayoutInflater inflater,
                             final ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        root = inflater.inflate(R.layout.fragment_home, container, false);
        final TextView textView = root.findViewById(R.id.text_home);
        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });

        Button btn_add_apero = (Button) root.findViewById(R.id.btn_add_apero);
        btn_add_apero.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(root.getContext());
                builder.setTitle("Super un nouvel apéro !");
                final EditText name_apero = (EditText)root.findViewById(R.id.edit_apero);
                final EditText date_apero = (EditText)root.findViewById(R.id.edit_date);

                builder.setView(inflater.inflate(R.layout.layout_dialog, null))
                        // Add action buttons
                        .setPositiveButton(R.string.text_add, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                LaperoDatabase db = Room.databaseBuilder(root.getContext(),
                                        LaperoDatabase.class, "lapero_db").allowMainThreadQueries().build();

                                AperoDao dbApero = db.getAperoDao();
                                Apero new_apero = new Apero(name_apero.getText().toString(), date_apero.getText().toString());
                                dbApero.insert(new_apero);
                            }
                        })
                        .setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                builder.show();
            }
        });
        return root;
    }

В моем layout_dialog.xml я установил 2 EditText:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <EditText
        android:id="@+id/edit_apero"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/edit_apero" />

    <EditText
        android:id="@+id/edit_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/edit_apero"
        android:layout_alignParentStart="true"
        android:hint="@string/edit_date"
        android:layout_alignParentLeft="true" />

</RelativeLayout>  

Как мне получить значение в этих 2 полях?

1 Ответ

1 голос
/ 04 марта 2020

Первое, что я заметил, это то, что вы используете root для поиска диалоговых окон, но root указывает на ваш фрагментный макет. root = inflater.inflate(R.layout.fragment_home, container, false);

Сначала надуйте макет вашего диалога, прежде чем ссылаться на его идентификатор ресурса.

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View inflater = getLayoutInflater().inflate(R.layout.layout_dialog, null);
builder.setView(inflater);

Затем измените root на inflater, чтобы вы ссылались вид из диалогового окна

 final EditText name_apero = (EditText)inflater.findViewById(R.id.edit_apero);
 final EditText date_apero = (EditText)inflater.findViewById(R.id.edit_date);

Полный код

Button btn_add_apero = (Button) root.findViewById(R.id.btn_add_apero);
btn_add_apero.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            View inflater = getLayoutInflater().inflate(R.layout.layout_dialog, null);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setView(inflater);
            builder.setTitle("Super un nouvel apéro !");

            final EditText name_apero = (EditText)inflater.findViewById(R.id.edit_apero);
            final EditText date_apero = (EditText)inflater.findViewById(R.id.edit_date);
                        // Add action buttons
                     builder.setPositiveButton(R.string.text_add, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                LaperoDatabase db = Room.databaseBuilder(root.getContext(),
                                        LaperoDatabase.class, "lapero_db").allowMainThreadQueries().build();

                                AperoDao dbApero = db.getAperoDao();
                                Apero new_apero = new Apero(name_apero.getText().toString(), date_apero.getText().toString());
                                dbApero.insert(new_apero);
                            }
                        })
                     builder.setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                builder.show();
            }
});
...