Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the date value from DatePickerDialog in Android?

I am new to android . I ve created a Date picker in android using following guide .http://developer.android.com/guide/topics/ui/controls/pickers.html

 public  class DatePickerFragment extends DialogFragment
  implements DatePickerDialog.OnDateSetListener {



StringBuilder sb = new StringBuilder();
public static String date;
    @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);

   // Create a new instance of DatePickerDialog and return it
   return new DatePickerDialog(getActivity(), this, year, month, day);
   }

  public void onDateSet(DatePicker view, int year, int month, int day) {
   // Do something with the date chosen by the user


sb.append(year);
sb.append('-');
sb.append(month+1);
sb.append('-');
sb.append(day);

date = sb.toString();
System.out.println("The date is "+date);

    }

I need to return this date value (date = sb.toString()) to my MainActivity . Since the onDateSet method is void what should I do ?

Additional Information - DatePickerDialog Triggers at the MainActivity class ,But not with single button click . There are several processes happens in side a single button , Date picker will triggers only when certain condition is met . I do not want to display the date value either . Just want it returned for further processing.

Appreciate any kind of guidance

Changed onDataset method and justshow()

public void onDateSet(DatePicker view, int year, int month, int day) {

// Do something with the date chosen by the user

    sb.append(year);
    sb.append('-');
    sb.append(month+1);
    sb.append('-');
    sb.append(day);

    date = sb.toString();
    MainActivity.newdate=sb.toString();
    System.out.println("The date is "+MainActivity.newdate);

} public void justShow(){

System.out.println("The date is "+MainActivity.newdate);

}

This is the relevant Part From Main(After making changes suggested in first reply )

    DateToken mydate=new DateToken();
    String test=dayvals.get(0);
    DialogFragment df=new DatePickerFragment();

    if(test.equalsIgnoreCase("day")){


        df.show(getSupportFragmentManager(), "DatePik");

    }

    System.out.println("Date is on Main"+newdate);


  DatePickerFragment dpf=new DatePickerFragment();
  dpf.justShow();

newdate is the static String , but still outputs null. In both MainActivity and justShow methods . But in onDataSet method date outputs correctly

like image 734
user1855222 Avatar asked Nov 27 '12 04:11

user1855222


2 Answers

  • You could create a public method in your DatePickerFragment to return the string.
  • You could have a static variable in your MainActivity that this class writes to.
  • You could use SharedPreferences to store the string.

I would go with the first option, it's the simplest if your application is basic.

There are multiple ways of going about this as you can see, so it's important to look at how the user interacts with your app and when that date is needed. The public return method is nice if you hold a reference to the Fragment in MainActivity and you don't need the data ASAP. The static variable is nice if you need the string changed as soon as the user chooses a date. The last method is wasteful and is least recommended, but there is no static "magic" being done.

like image 63
A--C Avatar answered Oct 07 '22 07:10

A--C


Although this was asked 4years ago and last active 1-year ago (as at my answering). I hope the below helps.

package com.example.fragments;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

/**
 * Date picker fragment bit 18/03/2017.
 */

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

  private OnDateSetListener callbackListener;

  /**
   * An interface containing onDateSet() method signature.
   * Container Activity must implement this interface.
   */
  public interface OnDateSetListener {
    void onDateSet(DatePicker view, int year, int month, int dayOfMonth);
  }

  /* (non-Javadoc)
   * @see android.app.DialogFragment#onAttach(android.app.Activity)
   */
  @Override
  public void onAttach(Context activity) {
    super.onAttach(activity);

    try {
      callbackListener = (OnDateSetListener) activity;

    } catch (ClassCastException e) {
      throw new ClassCastException(activity.toString() + " must implement OnDateSetListener.");
    }
  }

  @NonNull
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker
    final Calendar calendar = Calendar.getInstance(getResources().getConfiguration().locale);
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);

    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);
  }

  @Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    if (callbackListener != null) {
      callbackListener.onDateSet(view, year, month, dayOfMonth);
    }
  }
}

Then do next in MainActivity

    public class MainActivity extends AppCompatActivity implements View.OnClickListener, DatePickerFragment.OnDateSetListener {


  private EditText edittextDate;

  private Locale locale;

  private DialogFragment datePicker;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    locale = getResources().getConfiguration().locale;
    datePicker = new DatePickerFragment();

    edittextDate = (EditText) findViewById(R.id.edittextDate);
    edittextDate.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {

      case R.id.edittextDate: {
        datePicker.show(getSupportFragmentManager(), "datePicker");
        break;
      }
    }
  }

  @Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    final Calendar calendar = Calendar.getInstance(locale);
    final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);

    if (getCurrentFocus() != null) {
      switch (getCurrentFocus().getId()) {

        case R.id.edittextDate:
          calendar.set(year, month, dayOfMonth);
          edittextDate.setText(dateFormat.format(calendar.getTime()));
          break;
      }
    }
  }
}
like image 42
OliverTester Avatar answered Oct 07 '22 06:10

OliverTester