2014-09-02 44 views
0

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

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); 
    } 


} 

这里是我的日期选择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(" ")); 

    } 

任何帮助将不胜感激。

回答

0

我在我的应用程序之一做它的方式是: 1)就像你,我有一个文本字段来存储日期。所以我创建了setOnFocusChangeListener & setOnClickListener,它将创建一个DatePickerDialog,我们可以在其中滚动来设置我们的日期。你可以看到,在他们的内部,我打电话给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 

现在,你将不得不在文本框中的日期作为字符串,你可以保存在数据库中。我希望这会有所帮助。

+0

谢谢!你是一个拯救生命的人:) – DEADPOOL 2014-09-02 23:55:17

0

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

,并把你的代码

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年,int month,int day),恐怕它不起作用。

希望我说的很清楚

+0

感谢您的回复。你能说清楚你的答案吗?我对android开发不太熟悉。 – DEADPOOL 2014-09-02 10:10:41

相关问题