2

Guys i've created a custom date and time picker in my app now i'm using that picker several times . So, for avoiding the redundancy of code I thought i should put that function inside a separate function in another class from where i can call that whenever i need that but i'm not able to do so, Please help. The separate class is :

public class DateTimePicker {
    String str;

    public String returnDate(final Context ctx) {
        AlertDialog.Builder builder1 = new AlertDialog.Builder(ctx);
        final DatePicker picker1 = new DatePicker(ctx);

        try {
            Field f[] = picker1.getClass().getDeclaredFields();
            for (Field field : f) {
                if (field.getName().equals("mYearPicker")|| field.getName().equals("mYearSpinner") ) {
                    field.setAccessible(true);
                    Object yearPicker = new Object();
                    yearPicker = field.get(picker1);
                    ((View) yearPicker).setVisibility(View.GONE);
                }
            }
        } catch(Exception ex) {
            ex.printStackTrace();
        }
        picker1.setCalendarViewShown(false);

        builder1.setTitle("Please select date on which you would be leaving :")
            .setView(picker1)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    SimpleDateFormat parseFormat = new SimpleDateFormat("EEE dd MMM");
                    Date date1 = new Date();
                    date1.setDate(picker1.getDayOfMonth());
                    date1.setMonth(picker1.getMonth());
                    final String s = parseFormat.format(date1);
                    Log.e("DATE",s);

                    //Time picker
                    AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                    final TimePicker picker = new TimePicker(ctx);
                    picker.setIs24HourView(true);
                    builder.setTitle("Please select time at which you would be leaving :")
                        .setView(picker)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                int hour = picker.getCurrentHour();
                                int minute = picker.getCurrentMinute();
                                str = s + " " + hour + ":" + minute;
                            }
                        })
                        .setNegativeButton("One way", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.dismiss();
                            }
                        }).create().show();
                        //Time picker
                    }
                }
            )
            .setNegativeButton("One way", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.dismiss();
                }
            })
            .create().show();

        return "hello "+ str ;
    }

and the code from where i'm using the above class is :

DateTimePicker obj = new DateTimePicker();
Log.e("Object", "Created");
String st = obj.returnDate(this.getActivity());
Log.e("Function", "Called");
System.out.println("Value returned :" + st);
leaving.setText(st);

On log i'm getting "hello null" evething gets printed as soon as i called the function it is not even waiting for user input. please help thank you

hata
  • 11,633
  • 6
  • 46
  • 69
Brucode
  • 205
  • 1
  • 3
  • 12

5 Answers5

0

If you call show() the code won't stop and wait for a user input. Try adding:

[...]
}).create().show();
Log.i("Dialog", "Show called");

to understand what happens.

If you want to use the input data from your Dialog you have to call a function from within you positive button listener:

.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        int hour=picker.getCurrentHour();
        int minute=picker.getCurrentMinute();

        sendToSomewhere("+hour+":"+minute");
    }
})
Rüdiger
  • 1,674
  • 1
  • 20
  • 28
0

You will always get "hello null" back because the dialog internally creates a new thread and the answer of the dialog is only available in the respective button click listeners.

What you can do is to give a callback method to the function that creates the dialog and call this method once you have the answer in the dialog.

For inplementation details on how to pass a function as parameter see Java Pass Method as Parameter.

edit

On second thought, it is much more elegant to send the onClickListeners as the parameters of your dialog function.

You can define the onclick for all three last buttons in your flow like

DialogInterface.OnClickListener
     yesButton = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                    int hour = picker.getCurrentHour();
                    int minute = picker.getCurrentMinute();
                    str = s + " " + hour + ":" + minute;
                     SomeFunction();
            }
        });

And pass 3 of these objects to your dialog function that than needs a function header like

public void returnDate(final Context ctx, OnClickListener yes, OnClickListener no1, OnClickListener no2) {
Community
  • 1
  • 1
Niki van Stein
  • 10,564
  • 3
  • 29
  • 62
0

Basically you should define the method returning void. And to accept the user input String, you can use callback.

  • Get OnUserInputListener as a constructor arugment (though you can get it other way)
  • Define interface in the DateTimePicker class.

Your DateTimePicker class will be like below:

public class DateTimePicker {
    private final OnUserInputListener onUserInputListener;

    // String str; <-- this field value has no use

    DateTimePicker(OnUserInputListener onUserInputListener) {
        this.onUserInputListener = onUserInputListener;
    }

    public void returnDate(final Context ctx) {

        ...

        public void onClick(DialogInterface dialog, int whichButton) {
            int hour = picker.getCurrentHour();
            int minute = picker.getCurrentMinute();
            str = s + " " + hour + ":" + minute;
            onUserInputListener.onUserInput(str); // CALL BACK!!!
        }

        ...

    }

    public interface OnUserInputListener {
        void onUserInput(String string);
    }
}

For the caller side class, it should implement OnUserInputListener.

public class MainActivity extends Activity implements OnUserInputListener {

    ...

    DateTimePicker obj = new DateTimePicker(this);
    obj.returnDate(this.getActivity());

    ...

    @override
    public void onUserInput(String string) {
        System.out.println("Value returned :" + string);
        leaving.setText(string);
    }
}
hata
  • 11,633
  • 6
  • 46
  • 69
0

This may help you!

public class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {
    TextView textView, tv;

    public DatePickerFragment(TextView textView, TextView text) {
        this.textView = textView;
        tv = text;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        mCalendar.set(Calendar.YEAR, year);
        mCalendar.set(Calendar.MONTH, month);
        mCalendar.set(Calendar.DAY_OF_MONTH, day);
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        String dateForButton = dateFormat.format(mCalendar.getTime());
        textView.setText(dateForButton);
        tv.setVisibility(View.VISIBLE);
    }
}

and for show dialog

dateFragment = new DatePickerFragment(toDate, tvTo);
dateFragment.show(getFragmentManager(), "Dialog Title");

you can use it in activity/ custom class

Rajesh
  • 2,618
  • 19
  • 25
0

Try to add custom date selected listener in DateTimePicker :

public interface OnDateSelectedListener{
  public void onDateSelected(String date);
}

Add custom interface inside DateTimePicker and set listener reference returnDate :

public class DateTimePicker {

    public void returnDate(final Context ctx, final OnDateSelectedListener onDateSelectedListener) {
        AlertDialog.Builder builder1 = new AlertDialog.Builder(ctx);
        final DatePicker picker1 = new DatePicker(ctx);

        try {
            Field f[] = picker1.getClass().getDeclaredFields();
            for (Field field : f) {
                if (field.getName().equals("mYearPicker") || field.getName().equals("mYearSpinner")) {
                    field.setAccessible(true);
                    Object yearPicker = new Object();
                    yearPicker = field.get(picker1);
                    ((View) yearPicker).setVisibility(View.GONE);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        picker1.setCalendarViewShown(false);

        builder1.setTitle("Please select date on which you would be leaving :")
                .setView(picker1)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                SimpleDateFormat parseFormat = new SimpleDateFormat("EEE dd MMM");
                                Date date1 = new Date();
                                date1.setDate(picker1.getDayOfMonth());
                                date1.setMonth(picker1.getMonth());
                                final String s = parseFormat.format(date1);
                                Log.e("DATE", s);

                                //Time picker
                                AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                                final TimePicker picker = new TimePicker(ctx);
                                picker.setIs24HourView(true);
                                builder.setTitle("Please select time at which you would be leaving :")
                                        .setView(picker)
                                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                int hour = picker.getCurrentHour();
                                                int minute = picker.getCurrentMinute();
                                                onDateSelectedListener.onDateSelected(s + " " + hour + ":" + minute);
                                            }
                                        })
                                        .setNegativeButton("One way", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                dialog.dismiss();
                                            }
                                        }).create().show();
                            }
                        }
                )
                .setNegativeButton("One way", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                })
                .create().show();
    }

    public interface OnDateSelectedListener{
        public void onDateSelected(String date);
    }

}

Now call DateTimePicker with OnDateSelectedListener reference :

DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.returnDate(this.getActivity(), new DateTimePicker.OnDateSelectedListener() {
   @Override
   public void onDateSelected(String date) {
      leaving.setText(st);
   }
});
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67