save information of date picker

  • Replies:0
  • OpenNot stickiedUnanswered
  • Forum posts: 1

Oct 7, 2015, 3:53:49 PM via Website

hi I wonder how can I save the chosen date when I close my application
I see that I can use "sharedpreferences" but I don't understand how, pls help me
this is my code:

package puzzle.test;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends Activity {

    private TextView tvDisplayDate;

    TextView textView1;
    TextView textView2;
    TextView textView3;
    private DatePicker dpResult;
    private Button btnChangeDate;

    private int year;
    private int month;
    private int day;

    static final int DATE_DIALOG_ID = 999;

    public void onCreate(Bundle savedInstanceState) {



    // display current date
    public void setCurrentDateOnView() {

        tvDisplayDate = (TextView) findViewById(;
        dpResult = (DatePicker) findViewById(;

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

        // set current date into textview
        tvDisplayDate.setText(new StringBuilder()
                // Month is 0 based, just add 1
                .append(day).append("/").append(month + 1).append("/")
                .append(year).append(" "));


    public void addListenerOnButton() {

        btnChangeDate = (Button) findViewById(;

        btnChangeDate.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {





    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG_ID:
                // set date picker as current date
                return new DatePickerDialog(this, datePickerListener,
                        year, month,day);
        return null;
    private DatePickerDialog.OnDateSetListener datePickerListener
            = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth+1;
            day = selectedDay;
//date now

            // set selected date into textview
            tvDisplayDate.setText(new StringBuilder().append(day)
                    .append(" "));

            // set selected date into datepicker also
            dpResult.init(year, month, day, null);



Recommended articles