Home > database >  Trying to get Calendar data into a String
Trying to get Calendar data into a String

Time:04-18

Trying to store data into a string.

This is my utilities.

public class CommonDatePicker {

public static  void datePicker(final TextView textView, Context context) {
  Calendar dateCalender = Calendar.getInstance();
  final int year = dateCalender.get(Calendar.YEAR);
  final   int month = dateCalender.get(Calendar.MONTH);
  final int day = dateCalender.get(Calendar.DAY_OF_MONTH);


  DatePickerDialog datePickerDialog;
  datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
     @Override
     public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        monthOfYear = monthOfYear   1;
        //2001-05-03
        // dayOfMonth  monthOfYear
        String formattedMonth = ""   monthOfYear;
        String formattedDayOfMonth = ""   dayOfMonth;

        if(monthOfYear < 10){

           formattedMonth = "0"   monthOfYear;
        }
        if(dayOfMonth < 10){

           formattedDayOfMonth  = "0"   dayOfMonth ;
        }
        //editText.setText( formattedDayOfMonth   "-"   formattedMonth   "-"   year);
        textView.setText( year   "-"   formattedMonth   "-"   formattedDayOfMonth);

     }

  }, year, month, day);
  datePickerDialog.setTitle("SELECT DATE");
  datePickerDialog.show();
   }
 }

This is where I'm trying to get data. After clicking on textView the datePicker appears as expected but I want to store picked data into a string. I don't know how to do it.

This is my main.java

txt_data_collection_date.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            CommonDatePicker.datePicker(txt_data_collection_date, TofsilForm10Activity.this);
            //String date; I want to store data in date.
        }
    });

CodePudding user response:

Caveat, I am not an Android developer, so this may be a silly Answer.


By the way, the terrible Calendar class was supplanted years ago by the modern java.time classes defined in JSR 310. Android 26 comes with an implementation. For earlier Android, the latest tooling makes most of the java.time functionality available via “API desugaring”.

Replace this:

Calendar dateCalender = Calendar.getInstance();
final int year = dateCalender.get(Calendar.YEAR);
final   int month = dateCalender.get(Calendar.MONTH);
final int day = dateCalender.get(Calendar.DAY_OF_MONTH);

… with the following use of LocalDate. And note that unlike the legacy classes, java.time uses sane numbering with the year 2022 being 2022, and January-December being 1-12.

LocalDate ld = LocalDate.now() ;
final int year = ld.getYear() ;
final int month = ld.getMonthValue() ;
final int day = ld.getDayOfMonth() ;

The format you want for your text happens to comply with ISO 8601 standard. That standard’s formats are used by default in the java.time classes when generating/parsing text. So replace all this:

        monthOfYear = monthOfYear   1;
        //2001-05-03
        // dayOfMonth  monthOfYear
        String formattedMonth = ""   monthOfYear;
        String formattedDayOfMonth = ""   dayOfMonth;

        if(monthOfYear < 10){

           formattedMonth = "0"   monthOfYear;
        }
        if(dayOfMonth < 10){

           formattedDayOfMonth  = "0"   dayOfMonth ;
        }
        //editText.setText( formattedDayOfMonth   "-"   formattedMonth   "-"   year);
        textView.setText( year   "-"   formattedMonth   "-"   formattedDayOfMonth);

… with this:

        textView.setText( LocalDate.of( year, monthOfYear, dayOfMonth ).toString() ) ;

So that first piece of code could look like this. Notice how better indenting makes the code more obvious.

public class CommonDatePicker
{
    public static void datePicker ( final TextView textView , Context context )
    {
        LocalDate today = LocalDate.now();
        DatePickerDialog datePickerDialog =
                new DatePickerDialog(
                        context ,
                        new DatePickerDialog.OnDateSetListener()  // Implementing `DatePickerDialog.OnDateSetListener`.
                        {
                            @Override
                            public void onDateChanged ( DatePicker view , int year , int monthOfYear , int dayOfMonth )
                            {
                                textView.setText( LocalDate.of( year , monthOfYear , dayOfMonth ).toString() );
                            }
                        } ,
                        today.getYear() ,
                        today.getMonth() ,
                        today.getDayOfMonth()
                );
        datePickerDialog.setTitle( "SELECT DATE" );
        datePickerDialog.show();
    }
}

Having revamped that code, let's address your question, which apparently is that you want to save the user's chosen date into another place. I am just guessing at that given (a) your Comments, and (b) I cannot determine the purpose of your second code snippet.

Your onDateChanged method reacts to the user choosing a date in the date picker. There you generate your desired text. You store that text in textView. You could store it somewhere else too.

                            @Override
                            public void onDateChanged ( DatePicker view , int year , int monthOfYear , int dayOfMonth )
                            {
                                LocalDate chosenDate = LocalDate.of( year , monthOfYear , dayOfMonth ) ;
                                someOtherObject.someField = chosenDate.toString() ;
                                textView.setText( chosenDate.toString() );
                            }

Better yet, store the LocalDate on that other place, rather than mere text.

                            @Override
                            public void onDateChanged ( DatePicker view , int year , int monthOfYear , int dayOfMonth )
                            {
                                LocalDate chosenDate = LocalDate.of( year , monthOfYear , dayOfMonth ) ;
                                someOtherObject.someField = chosenDate ;
                                textView.setText( chosenDate.toString() );
                            }

Of course, global variables like someOtherObject.someField should generally be avoided. So pass it in just like you passed in TextView textView.

public void datePicker ( final LocalDate someLocalDateField, final TextView textView , Context context )

Perhaps a better approach is to make use of the CommonDatePicker class you have created. Change that datePicker method to be an instance method, not a static method. Add a member field to that class to carry the result of a user’s choice. And I would change the name of that method to be more descriptive such as makeDatePicker.

Kill the show call. Interrogate for the result afterwards.

public class CommonDatePicker
{
    private LocalDate chosenDate ;
    public LocalDate getChosenDate() { return this.chosenDate ; }
    public void makeDatePicker ( final TextView textView , Context context )
    {
        LocalDate today = LocalDate.now();
        DatePickerDialog datePickerDialog =
                new DatePickerDialog(
                        context ,
                        new DatePickerDialog.OnDateSetListener()  // Implementing `DatePickerDialog.OnDateSetListener`.
                        {
                            @Override
                            public void onDateChanged ( DatePicker view , int year , int monthOfYear , int dayOfMonth )
                            {
                                this.chosenDate = LocalDate.of( year , monthOfYear , dayOfMonth ) ;
                                textView.setText( this.chosenDate.toString() );
                            }
                        } ,
                        today.getYear() ,
                        today.getMonth() ,
                        today.getDayOfMonth()
                );
        datePickerDialog.setTitle( "SELECT DATE" );
    }
}

Usage:

CommonDatePicker commonDatePicker = new CommonDatePicker( context ) ;
DatePickerDialog datePicker = commonDatePicker.makeDatePicker() ;
datePicker.show() ;  // I assume this code blocks here until date picker is closed. (I don't know Android.)
LocalDate chosenDate = commonDatePicker.getChosenDate() ;

If the situation is such that the user may cancel the date picker without making a choice, then our LocalDate reference variable will be null. You could check for null. But better to return an Optional to indicate explicitly that null is an acceptable value value to be expected.

public Optional < LocalDate > getChosenDate() { return Optional.ofNullable ( this.chosenDate ) ; }

Usage:

CommonDatePicker commonDatePicker = new CommonDatePicker( context ) ;
DatePickerDialog datePicker = commonDatePicker.makeDatePicker() ;
datePicker.show() ;  // I assume this code blocks here until date picker is closed. (I don't know Android.)
LocalDate date = commonDatePicker.getChosenDate().orElse( existingLocalDate ) ;

Now we no longer need to pass in final TextView textView. Change your class to this.

public class CommonDatePicker
{
    private LocalDate chosenDate ;
    public Optional < LocalDate > getChosenDate() { return Optional.ofNullable( this.chosenDate ) ; }
    public void makeDatePicker ( Context context )
    {
        LocalDate today = LocalDate.now();
        DatePickerDialog datePickerDialog =
                new DatePickerDialog(
                        context ,
                        new DatePickerDialog.OnDateSetListener()  // Implementing `DatePickerDialog.OnDateSetListener`.
                        {
                            @Override
                            public void onDateChanged ( DatePicker view , int year , int monthOfYear , int dayOfMonth )
                            {
                                this.chosenDate = LocalDate.of( year , monthOfYear , dayOfMonth ) ;
                            }
                        } ,
                        today.getYear() ,
                        today.getMonth() ,
                        today.getDayOfMonth()
                );
        datePickerDialog.setTitle( "SELECT DATE" );
    }
}

Usage:

CommonDatePicker commonDatePicker = new CommonDatePicker( context ) ;
DatePickerDialog datePicker = commonDatePicker.makeDatePicker() ;
datePicker.show() ;  
LocalDate localDate = commonDatePicker.getChosenDate().orElse( existingLocalDate ) ;
someOtherPlace.updateDate( localDate ) ;
textView.setText( localDate.toString() ) ;

After all these changes, notice how we have pulled outside of CommonDatePicker all the parts that are extraneous. Now that class can “mind its own business”, without knowing or caring about other pieces of your app. Its job is simply to gather input from the user, not update various parts of your app.

We could further simplify the code, so the calling app does not need to know about the use of DatePickerDialog. We could drop the makeDatePicker(), and add a show method instead. With a show method in place, we can skip the interrogation step, and just have show return the Optional < LocalDate > object.

And rather than assume the dialog should initialize to today's date, accept a date in its constructor.

public class CommonDatePicker
{
    private DatePickerDialog datePickerDialog;
    private LocalDate chosenDate;

    public CommonDatePicker ( final Context context , final LocalDate initialDate )
    {
        this.datePickerDialog =
                new DatePickerDialog(
                        context ,
                        new DatePickerDialog.OnDateSetListener()  // Implementing `DatePickerDialog.OnDateSetListener`.
                        {
                            @Override
                            public void onDateChanged ( DatePicker view , int year , int monthOfYear , int dayOfMonth )
                            {
                                this.chosenDate = LocalDate.of( year , monthOfYear , dayOfMonth );
                            }
                        } ,
                        initialDate.getYear() ,
                        initialDate.getMonth() ,
                        initialDate.getDayOfMonth()
                );
        this.datePickerDialog.setTitle( "SELECT DATE" );
    }

    public Optional < LocalDate > show ( ) { 
        this.datePickerDialog.show() ;  // I assume code blocks here until user choses a date. (I don't know Android.)
        return Optional.ofNullable( this.chosenDate ); 
    }
}

Usage:

LocalDate yesterday = LocalDate.now().minusDays( 1 ) ;
Optional < LocalDate > optionalChosenDate = new CommonDatePicker( context , yesterday ).show() ;
someOtherPlace.updateDate( optionalChosenDate.orElse( yesterday ) ) ;
textView.setText( optionalChosenDate.orElse( yesterday ).toString() ) ;

Now the calling programmer need know nothing about the DatePickerDialog we happen to be using internally in our CommonDatePicker class. The calling programmer needs to learn only our simple API. That API consists of two parts: A constructor taking a Context and a LocalDate, and a show method that interacts with user to return an optional LocalDate object.

  • Related