A
A
andrej33372021-07-27 12:39:03
Java
andrej3337, 2021-07-27 12:39:03

How to get data from a nested listener method and then use it outside of it?

The application uses a button that displays the current date, when clicked, a spinner for selecting an arbitrary date appears. After selecting a date, the button displays the selected date.

There is a listener method

private void initDatePicker()
        {
                DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener()
                {
                        @Override
                        public void onDateSet(DatePicker datePicker, int year, int month, int day)
                        {
                                month = month + 1;
                                date = makeDateString(day, month, year);
                                dateButton.setText(date); //<--- здесь кнопке передается дата сетом
                        }
                                                                     /**А за пределами скобок выше даже публичные переменные, объявленные в текущем классе, которым присвоены данные из переменной  date, являются пустыми.**/
                };
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH);
                int day = cal.get(Calendar.DAY_OF_MONTH);

                int style = AlertDialog.THEME_HOLO_DARK;

                datePickerDialog = new DatePickerDialog(this, style, dateSetListener, year, month, day);
        }

So for me, this nested method has become a "black hole" that releases data.

I do not need to transfer them to the xml view, otherwise I would do it in the image with dateButton.setText(date);, I need to use the date received when the user selects it in the same class, but in other methods (functions).

How can I do that?

Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-07-27
@andrej3337

You must understand that the listener is needed in order to perform any actions asynchronously. This is its meaning. If you want some code to be executed when a date is selected, you need to explicitly call it from the listener.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question