2014-09-02 57 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

相關問題