如何将从DatePicker检索到的数据保存到数据库?

时间:2014-09-02 09:43:09

标签: android datepicker

我是Android开发的新手。我希望你能帮助我如何将从dialogfragment中检索到的数据保存到我的数据库。我当前的代码能够保存数据,但只保存当前日期而不是所选日期。

public class RemindersFragment extends Fragment  {


    private EditText mTitleText;
    private EditText mBodyText;
    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm:ss";
    private Button mConfirmButton;
    private Long mRowId;
    private RemindersDbAdapter mDbHelper;
    private Calendar mCalendar;

    Button btnChangeDate,btnChangeTime;
    TextView txtDisplayDate,txtDisplayTime;


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

    private int hour;
    private int minute;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
         mDbHelper = new RemindersDbAdapter(getActivity());

        View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
          mCalendar = Calendar.getInstance(); 
            mTitleText = (EditText) rootView.findViewById(R.id.title);
            mBodyText = (EditText) rootView.findViewById(R.id.body);
            mConfirmButton = (Button) rootView.findViewById(R.id.confirm);
            btnChangeDate = (Button) rootView.findViewById(R.id.btnChangeDate);
            btnChangeTime = (Button) rootView.findViewById(R.id.btnChangeTime);
            txtDisplayTime = (TextView) rootView.findViewById(R.id.txtTime);
            txtDisplayDate = (TextView) rootView.findViewById(R.id.txtDate);
            mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID) 
                                                : null;

            registerButtonListenersAndSetDefaultText();

            btnChangeDate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDatePickerDialog();
                }
            });

            btnChangeTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showTimePickerDialog();
                }
            });


        return rootView;
    }


    // display current date
        public void showCurrentDateOnView() {

            year = mCalendar.get(Calendar.YEAR);
            month = mCalendar.get(Calendar.MONTH);
            day = mCalendar.get(Calendar.DAY_OF_MONTH);

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

        }


        // display current time
        public void showCurrentTimeOnView() {

            hour = mCalendar.get(Calendar.HOUR_OF_DAY);
            minute = mCalendar.get(Calendar.MINUTE);

            // set current time into textview
            txtDisplayTime.setText(
                        new StringBuilder().append(hour)
                                           .append(":").append(minute));

        }


    private void setRowIdFromIntent() {
        if (mRowId == null) {
            Bundle extras = getActivity().getIntent().getExtras();            
            mRowId = extras != null ? extras.getLong(RemindersDbAdapter.KEY_ROWID) 
                                    : null;

        }
    }

    public void showDatePickerDialog() {
        DatePickerFragment newFragment = new DatePickerFragment(txtDisplayDate);
        newFragment.show(getFragmentManager(), "datePicker");

    }

    public void showTimePickerDialog() {
        TimePickerFragment newFragment = new TimePickerFragment(txtDisplayTime);
        newFragment.show(getFragmentManager(), "timePicker");
    }



    @Override
    public void onPause() {
        super.onPause();
        mDbHelper.close(); 
    }

    @Override
    public void onResume() {
        super.onResume();
        mDbHelper.open(); 
        setRowIdFromIntent();
        populateFields();
    }


    private void registerButtonListenersAndSetDefaultText() {

        mConfirmButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent;
                saveState(); 
                getActivity().setResult(Activity.RESULT_OK);
                Toast.makeText(getActivity(), getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity().getApplication(), Manage_Settings.class);
                startActivity(intent);
            }

        });

         showCurrentDateOnView();
            showCurrentTimeOnView();

    }

    private void populateFields()  {



        // Only populate the text boxes and change the calendar date
        // if the row is not null from the database. 
        if (mRowId != null) {
            Cursor reminder = mDbHelper.fetchReminder(mRowId);
            getActivity().startManagingCursor(reminder);
            mTitleText.setText(reminder.getString(
                    reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_TITLE)));
            mBodyText.setText(reminder.getString(
                    reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_BODY)));


            // Get the date from the database and format it for our use. 
            SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
            Date date = null;
            try {
                String dateString = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_DATE_TIME)); 
                date = dateTimeFormat.parse(dateString);
                mCalendar.setTime(date); 
            } catch (ParseException e) {
                Log.e("ReminderEditActivity", e.getMessage(), e); 
            } 
        } else {
            // This is a new task - add defaults from preferences if set. 
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); 
            String defaultTitleKey = getString(R.string.pref_task_title_key); 
            String defaultTimeKey = getString(R.string.pref_default_time_from_now_key); 

            String defaultTitle = prefs.getString(defaultTitleKey, null);
            String defaultTime = prefs.getString(defaultTimeKey, null); 

            if(defaultTitle != null)
                mTitleText.setText(defaultTitle); 

            if(defaultTime != null)
                mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));

        }

         showCurrentDateOnView();
            showCurrentTimeOnView();

    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);
    }



    @SuppressLint("SimpleDateFormat")
    private void saveState() {
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);        
        String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());

        if (mRowId == null) {

            long id = mDbHelper.createReminder(title, body, reminderDateTime);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateReminder(mRowId, title, body, reminderDateTime);
        }

        new ReminderManager(getActivity()).setReminder(mRowId, mCalendar); 
    }


}

这是我的Datepicker DialogFragment:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{

    TextView txtDate;


     public DatePickerFragment(TextView txtDate) {
        super();
        this.txtDate = txtDate;
    }

    @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) {
            //DatePickerFragmentListener listener = (DatePickerFragmentListener) getTargetFragment();

            txtDate.setText(new StringBuilder().append(month + 1)
                   .append("-").append(day).append("-").append(year)
                   .append(" "));
        }



}

到目前为止我做了什么:

我试图在当前日期设置mCalendar,但我认为我做得不对:

// display current date
    public void showCurrentDateOnView() {

        year = mCalendar.get(Calendar.YEAR);
        month = mCalendar.get(Calendar.MONTH);
        day = mCalendar.get(Calendar.DAY_OF_MONTH);

        mCalendar.set(Calendar.YEAR, year);
        mCalendar.set(Calendar.MONTH, month);
        mCalendar.set(Calendar.DAY_OF_MONTH, day);
        // set current date into textview
        txtDisplayDate.setText(new StringBuilder()
            // Month is 0 based, just add 1
            .append(month + 1).append("-").append(day).append("-")
            .append(year).append(" "));

    }

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:0)

也许你应该从类DatePickerFragment中的DatePickerDialog覆盖onDateChanged方法(DatePicker视图,int year,int month,int day)。

并输入您的代码

   txtDisplayDate.setText(new StringBuilder()
        // Month is 0 based, just add 1
        .append(month + 1).append("-").append(day).append("-")
        .append(year).append(" "));

进入该方法。

我当前的代码可以保存数据,但只保存当前日期而不是所选日期。

所以,我想也许你的问题是你无法获得所选的日期。

我建议您覆盖子类DatePickerDialog的方法 http://developer.android.com/reference/android/app/DatePickerDialog.html

DatePickerDialog已经实现了OnDateChangedListener,因此它可以处理日期更改内容。而你只是使用它。

你在DatePickerFragment中定义了一个方法onDateSet(DatePicker视图,int year,int month,int day),我担心它不起作用。

希望我说清楚

答案 1 :(得分:0)

我在我的一个应用程序中完成它的方式是: 1)就像你一样,我有一个TextField来存储日期。所以我创建了setOnFocusChangeListener& setOnClickListener将创建一个DatePickerDialog,我们可以滚动它来设置我们的日期。

txtDOB.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus){
            CallenderCall();
        }
    }
});

txtDOB.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        CallenderCall();        
    }
});  

正如你所看到的,我在他们里面叫CallenderCall();这是:

public void CallenderCall(){
    //Creates new instance of calendar, get current Year, Month and Day and use it as default values for the Date Picker Dialog.
    final Calendar c = Calendar.getInstance();

    todayYear = c.get(Calendar.YEAR);
    todayMonth = c.get(Calendar.MONTH);
    todayDay = c.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog dpdFromDate = new DatePickerDialog(getActivity(), mDateSetListener, todayYear, todayMonth, todayDay);
    dpdFromDate.show();
}

我们可以看到这个CallenderCall会创建DatePickerDialog,因此需要另外一个函数来使它全部工作:

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    // onDateSet method
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {


        if (year > todayYear || year >= todayYear &&  monthOfYear > todayMonth || year >= todayYear &&  monthOfYear >= todayMonth && dayOfMonth > todayDay) {
            Toast.makeText(getActivity().getApplicationContext(), "Date of Birth can't be from the future ;)", Toast.LENGTH_LONG).show();
            txtDOB.setText("");
        }else{
            dateOfBirth = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear+1) + "/" + String.valueOf(year);
            txtDOB.setText(dateOfBirth);
            Log.v("MAD","Date: "+dateOfBirth);   
        }



    } 
}; // DatePickerDialog.OnDateSetListener close 

现在,您将在文本框中将日期作为字符串,您可以将其保存在数据库中。我希望它会有所帮助。