2012-08-04 73 views
0

我想我可能会在一篇文章中提出太多问题,所以让我知道是否应该将其分解为单独的日期和时间问题,但利用日期和时间在数据库中我彻底难倒了。我研究过各种方法(字符串,juliandates,unix等),它所做的一切让我更加困惑。为了提供一些上下文,用户通过填写​​表单来添加记录。该表单有2个按钮,一个用datepicker打开一个片段,另一个用timepicker打开一个片段。所选日期和时间显示为按钮文本。另一个按钮将表单细节保存到数据库中。按时间和日期存储,检索和整理记录

接下来,我有一个列表视图活动,此时显示所有记录,但我最终希望有一个按钮到日期选择器片段,以便只显示具有特定日期的记录。那些记录按时间顺序列出。 (我认为一旦解决了下一段,我就可以自己弄清楚这个段落。)

点击列表视图中的某条记录会打开一个活动,其外观与原始表单相同(创建记录的位置)并从该记录中填入所有信息。用户然后可以选择删除记录,或者修改记录中的字段并保存(更新)记录。这个表格还应该包含一个日期和时间按钮,这样它们也可以改变,所以选择器应该被设置为以前保存在这个活动中的日期/时间。

我需要什么帮助,是存储日期和时间,然后检索,并在编辑表单以后编辑它,包括它格式化成一个特定的方法来显示的按钮文本的最佳方法(DD/MM/yyyy日期和hh:mm:am/pm时间)。正如前面提到的,这让我很困惑,所以我真的很感激有些人用这种方式持有。对于下面的大量代码抱歉,但我试图通过删除所有额外的表单域来保持它的相关性。

FuncAdd.java(形式来保存数据):

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView (R.layout.dash_add); 

    now = Calendar.getInstance(); 
    add_button_date = (Button) findViewById(R.id.add_button_date); 
    add_button_time = (Button) findViewById(R.id.add_button_time); 

    add_button_date.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH))+"/"+ 
      String.valueOf(now.get(Calendar.MONTH)+1)+"/"+ 
      String.valueOf(now.get(Calendar.YEAR))); 
    strDate = add_button_date.getText().toString(); 

    add_button_time.setText(String.valueOf(now.get(Calendar.HOUR_OF_DAY))+":"+ 
      String.valueOf(now.get(Calendar.MINUTE))); 
} 

public void addDateTime(View v) { 
    int id = v.getId(); 
    switch (id) { 
    case R.id.add_button_date : 
     showDialogDate(); 
     break; 
    case R.id.add_button_time : 
     showDialogTime(); 
     break; 
    default: 
     break; 
}} 

public interface DateDialogFragmentListener { 
    public void updateChangedDate(int year, int month, int day); 
} 

public interface TimeDialogFragmentListener { 
    public void updateChangedTime(int hourOfDay, int minute); 
} 

public void showDialogDate() { 
    FragmentTransaction ftDate = getFragmentManager().beginTransaction(); 
    fragDate = DateDialogFragment.newInstance(this, new DateDialogFragmentListener() { 
     public void updateChangedDate(int year, int month, int day) { 
      add_button_date.setText(String.valueOf(day)+"/"+String.valueOf(month+1)+"/"+String.valueOf(year)); 
      now.set(Calendar.YEAR, year); 
      now.set(Calendar.MONTH, month); 
      now.set(Calendar.DAY_OF_MONTH, day); 
     }}, now); 
    fragDate.show(ftDate, "DateDialogFragment"); 
} 

public void showDialogTime() { 
    FragmentTransaction ftTime = getFragmentManager().beginTransaction(); 
    fragTime = TimeDialogFragment.newInstance(this, new TimeDialogFragmentListener() { 
     public void updateChangedTime(int hourOfDay, int minute) { 
      add_button_time.setText(String.valueOf(hourOfDay)+":"+String.valueOf(minute)); 
      now.set(Calendar.HOUR_OF_DAY, hourOfDay); 
      now.set(Calendar.MINUTE, minute); 
     }}, now); 
    fragTime.show(ftTime, "TimeDialogFragment"); 
} 

public void onClick(View arg0) { 

    strDate = add_button_date.getText().toString(); 
    strTime = add_button_time.getText().toString(); 

    String Time = strTime; 
    String Date = strDate; 
AddDBHelper entry = new AddDBHelper(FuncAdd.this); 
    entry.open(); 
    entry.createEntry(Time, Date, Category, CategoryPos, BGL, Carbs, Insulin, InsulinPos, Dose, CorInsulin, CorInsulinPos, CorDose); 
    entry.close();    

    goHome (this); 
} 

AddDBHelper.java(我的DB Helper类):

private static class DbHelper extends SQLiteOpenHelper { 

    public DbHelper(Context context) { 
     super(context, DB_NAME, null, DB_VERSION); 
    } 


    @Override 
    public void onCreate(SQLiteDatabase db) { 
     db.execSQL("CREATE TABLE " + DB_TABLE + " (" + 
      KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 
      KEY_TIME + " TEXT NOT NULL, " + 
      KEY_DATE + " TEXT NOT NULL, " + 
      KEY_CATEG + " TEXT NOT NULL);" 
);} 

public long createEntry(String Time, String Date, String Category) { 
    ContentValues cv = new ContentValues(); 
    cv.put(KEY_TIME, Time); 
    cv.put(KEY_DATE, Date); 
    cv.put(KEY_CATEG, Category); 
    return glucoDB.insert(DB_TABLE, null, cv); 
} 

public Cursor getEntries() {   
    return glucoDB.query(DB_TABLE, new String[] { 
      KEY_ROWID, 
      KEY_TIME, 
      KEY_DATE, 
      KEY_CATEG}, 
      null, null, null, null, null); 
} 

public void updateDetails(DBDetails dbdetails) { 

    ContentValues cv = new ContentValues(); 
    cv.put(AddDBHelper.KEY_TIME, UpdateDBDetails.newTime); 
    cv.put(AddDBHelper.KEY_DATE, UpdateDBDetails.newDate); 
    cv.put(AddDBHelper.KEY_CATEG, dbdetails.getuCateg()); 

    int count = glucoDB.update(DB_TABLE, cv, KEY_ROWID + "=?", new String[] {String.valueOf(dbdetails.getuRow())}); 
    Log.v("AddDbHelper", "Row " + dbdetails.getuRow() + " updated? " + count); 
} 

* TimeDialogFragment类:*

public class TimeDialogFragment extends DialogFragment { 

static Context mContext; 
static int mHour; 
static int mMinute; 
static TimeDialogFragmentListener mListener; 

public static TimeDialogFragment newInstance(Context context, 
     TimeDialogFragmentListener listener, Calendar now) { 
    TimeDialogFragment dialog = new TimeDialogFragment(); 
    mContext = context; 
    mListener = listener; 

    mHour = now.get(Calendar.HOUR_OF_DAY); 
    mMinute = now.get(Calendar.MINUTE); 

    Bundle args = new Bundle(); 
    args.putString("title", "Set Time"); 
    dialog.setArguments(args); 
    return dialog; 
} 

public Dialog onCreateDialog(Bundle savedInstanceState) { 
    return new TimePickerDialog(mContext, mTimeSetListener, mHour, mMinute, false); 
} 

private TimePickerDialog.OnTimeSetListener mTimeSetListener = 
     new TimePickerDialog.OnTimeSetListener() { 

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 
     mHour = hourOfDay; 
     mMinute = minute; 
     mListener.updateChangedTime(hourOfDay, minute); 
    } 
}; } 

DateDialogFragment类:

public class DateDialogFragment extends DialogFragment { 

static Context mContext; 
static int mYear; 
static int mMonth; 
static int mDay; 
static DateDialogFragmentListener mListener; 

public static DateDialogFragment newInstance(Context context, 
     DateDialogFragmentListener listener, Calendar now) { 
    DateDialogFragment dialog = new DateDialogFragment(); 
    mContext = context; 
    mListener = listener; 

    mYear = now.get(Calendar.YEAR); 
    mMonth = now.get(Calendar.MONTH); 
    mDay = now.get(Calendar.DAY_OF_MONTH); 

    Bundle args = new Bundle(); 
    args.putString("title", "Set Date"); 
    dialog.setArguments(args); 
    return dialog;   
} 

public Dialog onCreateDialog(Bundle savedInstanceState) { 
    return new DatePickerDialog(mContext, mDateSetListener, 
      mYear, mMonth, mDay); 
} 

private DatePickerDialog.OnDateSetListener mDateSetListener = 
     new DatePickerDialog.OnDateSetListener() { 

    public void onDateSet(DatePicker view, int year, int monthOfYear, 
      int dayOfMonth) { 
     mYear = year; 
     mMonth = monthOfYear; 
     mDay = dayOfMonth; 
     mListener.updateChangedDate(year, monthOfYear, dayOfMonth);  
      } 
    };} 

DBDetails.java(类获取/设定值):

public class DBDetails { 

private String uRow; 
private String uTime; 
private String uDate; 
private String uCateg; 

public String getuRow() { 
    return uRow; 
} 

public void setuRow(String uRow) { 
    this.uRow = uRow; 
} 

public String getuTime() { 
    return uTime; 
} 

public void setuTime(String uTime) { 
    this.uTime = uTime; 
} 

public String getuDate() { 
    return uDate; 
} 

public void setuDate(String uDate) { 
    this.uDate = uDate; 
} 

public String getuCateg() { 
    return uCateg; 
} 

public void setuCateg(String uCateg) { 
    this.uCateg = uCateg; 
} } 

UpdateDBDetails.java(类,其中用户可以编辑记录):

public class UpdateDBDetails extends DashMenuActivity { 

TimeDialogFragment fraguTime; 
DateDialogFragment fraguDate; 
Button update_button_time, update_button_date; 
Calendar now; 

ImageButton update_button_save, update_button_delete; 
String strTime, strDate; 

private String bundleduRowId; 
private String bundleduTime; 
private String bundleduDate; 
private String bundleduCateg; 
public static String getRowId; 
public static String newTime, newDate, newCat; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.updatedbdetails); 

    now = Calendar.getInstance(); 
    update_button_date = (Button) findViewById(R.id.update_button_date); 
    update_button_time = (Button) findViewById(R.id.update_button_time); 

    update_button_date.setText(bundleduDate); 
    update_button_time.setText(bundleduTime); 

Bundle takeBundledData = getIntent().getExtras(); 

    bundleduRowId = takeBundledData.getString("clickeduRowId"); 
    bundleduTime = takeBundledData.getString("clickeduTime"); 
    bundleduDate = takeBundledData.getString("clickeduDate"); 
    bundleduCateg = takeBundledData.getString("clickeduCateg"); 
} 
public void clickUpdateDelete(View v) { 
    newTime = strTime; 
    newDate = strDate; 
    newCateg = newCat; 

AddDBHelper modifyEntry = new AddDBHelper(this); 
    modifyEntry.open(); 

    DBDetails dbdetails = new DBDetails(); 

    dbdetails.setuRow(bundleduRowId); 

    if (v.getId() == R.id.update_button_delete) { 
     modifyEntry.deleteDetails(dbdetails); 
    } else if (v.getId() == R.id.update_button_save) { 
     dbdetails.setuDate(newDate); 
     dbdetails.setuTime(newTime); 
     dbdetails.setuCateg(newCateg); 
modifyEntry.updateDetails(dbdetails); 
    } 
    modifyEntry.close(); 
    finish(); 
} 

修正案FuncAdd.java类

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView (R.layout.dash_add); 

    add_button_date = (Button) findViewById(R.id.add_button_date); 
    add_button_time = (Button) findViewById(R.id.add_button_time); 

    now = Calendar.getInstance().getTime(); 

    SimpleDateFormat dFormatter = new SimpleDateFormat("dd MMM yyyy"); 
    strDate = dFormatter.format(now); 
    add_button_date.setText(strDate); 

    SimpleDateFormat tFormatter = new SimpleDateFormat("KK:mm a"); 
    strTime = tFormatter.format(now); 
    add_button_time.setText(strTime); 
} 

public interface DateDialogFragmentListener { 
    public void updateChangedDate(int year, int month, int day); 
} 

public void showDialogDate() { 
    FragmentTransaction ftDate = getFragmentManager().beginTransaction(); 
    fragDate = DateDialogFragment.newInstance(this, new DateDialogFragmentListener() { 
     public void updateChangedDate(int year, int month, int day) { 
      strDate = (String.valueOf(day)+"/"+String.valueOf(month+1)+"/"+String.valueOf(year)); 
      SimpleDateFormat dFormatter = new SimpleDateFormat("dd MMM yyyy"); 
      newstrDate = dFormatter.parse(strDate); 
      add_button_date.setText(newstrDate); 
     }}, now); 
    fragDate.show(ftDate, "DateDialogFragment"); 
} 

修订UpdateDBDetails。java

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.updatedbdetails); 

Bundle takeBundledData = getIntent().getExtras(); 

    bundleduRowId = takeBundledData.getString("clickeduRowId"); 
    bundleduTime = takeBundledData.getString("clickeduTime"); 
    bundleduDate = takeBundledData.getString("clickeduDate"); 

SimpleDateFormat dFormatter = new SimpleDateFormat("dd MMM yyyy"); 
    SimpleDateFormat tFormatter = new SimpleDateFormat("KK:mm a"); 

    now = Calendar.getInstance(); 

// no need to catch an exception, as I'm using pickers and the format can never be input incorrectly 
    try { 
     dDate = dFormatter.parse(bundleduDate); 
     String dateArray[] = dDate.toString().split(" "); 

     if (dateArray[1].equalsIgnoreCase("Jan")) { 
      uMonth = 0; 
     } else if (dateArray[1].equalsIgnoreCase("Feb")) { 
      uMonth = 1; 
     } else if (dateArray[1].equalsIgnoreCase("Mar")) { 
      uMonth = 2; 
     } else if (dateArray[1].equalsIgnoreCase("Apr")) { 
      uMonth = 3; 
     } else if (dateArray[1].equalsIgnoreCase("May")) { 
      uMonth = 4; 
     } else if (dateArray[1].equalsIgnoreCase("Jun")) { 
      uMonth = 5; 
     } else if (dateArray[1].equalsIgnoreCase("Jul")) { 
      uMonth = 6; 
     } else if (dateArray[1].equalsIgnoreCase("Aug")) { 
      uMonth = 7; 
     } else if (dateArray[1].equalsIgnoreCase("Sep")) { 
      uMonth = 8; 
     } else if (dateArray[1].equalsIgnoreCase("Oct")) { 
      uMonth = 9; 
     } else if (dateArray[1].equalsIgnoreCase("Nov")) { 
      uMonth = 10; 
     } else if (dateArray[1].equalsIgnoreCase("Dec")) { 
      uMonth = 11; 
     } 

     int uYear = Integer.parseInt(dateArray[5]); 
     int uDay = Integer.parseInt(dateArray[2]); 
     now.set(Calendar.YEAR, uYear); 
     now.set(Calendar.MONTH, uMonth); 
     now.set(Calendar.DAY_OF_MONTH, uDay); 
     CurrentD = now.getTime(); 
     strDate = dFormatter.format(CurrentD); 
     update_button_date.setText(strDate); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 

    try { 
     tDate = tFormatter.parse(bundleduTime); 
     String timeArrayFull[] = tDate.toString().split(" "); 
     String timeArray[] = timeArrayFull[3].split(":"); 
     int uHour = Integer.parseInt(timeArray[0]); 
     int uMinute = Integer.parseInt(timeArray[1]); 
     now.set(Calendar.HOUR_OF_DAY, uHour); 
     now.set(Calendar.MINUTE, uMinute); 
     CurrentT = now.getTime(); 
     strTime = tFormatter.format(CurrentT); 
     update_button_time.setText(strTime); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
\\ The rest of the code does not differ from above, for launching a dialogfragment and saving the results to the DB. 
+1

使用SimpleDateFormatter和Comparator。 – 2012-08-04 05:37:11

+1

[见-1](http://stackoverflow.com/questions/9912331/sorting-by-date-an-array-of-bean-having-date-member)和[见BlackBelt的链接](http:// stackoverflow.com/questions/9912574/sorting-list-having-itembean-by-date) – 2012-08-04 05:38:29

回答

0

使用Chintan建议的格式化程序,以及更多的阅读内容,我设法弄明白了。 Andy,你的建议很有价值,但是我已经获得了更多的帮助,如何使用dialogfragment设置/获取数据以允许保存,检索和更新数据库。最后,我只需要修改我的主要表单活动。

public class FuncAdd extends DashMenuActivity implements OnClickListener { 

TimeDialogFragment fragTime; 
DateDialogFragment fragDate; 
Button add_button_time, add_button_date; 
Calendar now; 
Date nowDT, newD, newT; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView (R.layout.dash_add); 

    add_button_date = (Button) findViewById(R.id.add_button_date); 
    add_button_time = (Button) findViewById(R.id.add_button_time); 

    now = Calendar.getInstance(); 
    nowDT = now.getTime(); 

    SimpleDateFormat dFormatter = new SimpleDateFormat("dd MMM yyyy"); 
    strDate = dFormatter.format(nowDT); 
    add_button_date.setText(strDate); 

    SimpleDateFormat tFormatter = new SimpleDateFormat("KK:mm a"); 
    strTime = tFormatter.format(nowDT); 
    add_button_time.setText(strTime); 
} 

public void addDateTime(View v) { 
    int id = v.getId(); 
    switch (id) { 
    case R.id.add_button_date : 
     showDialogDate(); 
     break; 
    case R.id.add_button_time : 
     showDialogTime(); 
     break; 
    default: 
     break; 
}} 

public interface DateDialogFragmentListener { 
    public void updateChangedDate(int year, int month, int day); 
} 

public interface TimeDialogFragmentListener { 
    public void updateChangedTime(int hourOfDay, int minute); 
} 

public void showDialogDate() { 
    FragmentTransaction ftDate = getFragmentManager().beginTransaction(); 
    fragDate = DateDialogFragment.newInstance(this, new DateDialogFragmentListener() { 
     public void updateChangedDate(int year, int month, int day) {    
      now.set(Calendar.YEAR, year); 
      now.set(Calendar.MONTH, month); 
      now.set(Calendar.DAY_OF_MONTH, day); 
      newD = now.getTime(); 
      SimpleDateFormat newDFormatter = new SimpleDateFormat("dd MMM yyyy"); 
      strDate = newDFormatter.format(newD); 
      add_button_date.setText(strDate); 
     }}, now); 
    fragDate.show(ftDate, "DateDialogFragment"); 
} 

public void showDialogTime() { 
    FragmentTransaction ftTime = getFragmentManager().beginTransaction(); 
    fragTime = TimeDialogFragment.newInstance(this, new TimeDialogFragmentListener() { 
     public void updateChangedTime(int hourOfDay, int minute) { 
      now.set(Calendar.HOUR_OF_DAY, hourOfDay); 
      now.set(Calendar.MINUTE, minute); 
      newT = now.getTime(); 
      SimpleDateFormat tFormatter = new SimpleDateFormat("KK:mm a"); 
      strTime = tFormatter.format(newT); 
      add_button_time.setText(strTime); 
     }}, now); 
    fragTime.show(ftTime, "TimeDialogFragment"); 
} 
} 
1

那么我真的不明白你为什么难倒了。但我猜如果你是关系数据库的新手,那么初学者可以理解这个问题。存储日期和时间的最佳方法是采用大多数数据库易于理解的格式,即使您不打算导出它。查看SQLite网站。要做到这一点,只需将它们作为字符串存储在数据库中的YYYY-MM-DD(日期)和HH:MM:SS(时间)格式。然后你可以使用SQLite的内置函数,你可以在我提供的链接上看到:)希望它有帮助。

编辑:关于日期

我还做了一点点额外的挖掘,因为我发现我的应用程序实际存储日期和时间为整数值,检查出的SQLite不同data types,但更重要的是你,第1.2节和时间数据类型。所以拿着他们作为TEXTINTEGER是好的,只要一致。

+0

谢谢。我熟悉存储和检索,因为我已经完成了其余的表单元素。我曾预料过,我会把它作为一个字符串存储,然后分割它,以便为新的采集器设置日期/时间。我现在已经改变了FuncAdd.java(请参阅原始帖子的修改)以使用日期对象而不是日历,但我不知道如何修改datepicker对话框和showDialogDate()方法。道歉,但我很新的编码,因此要求一些手持。 – Ronnie 2012-08-04 10:30:32

+0

啊,是的。你在正确的轨道上。我就是做这个的。只要将它们从数据库中取出就可以将它们分开。没有太多的工作。并且记得在将它输入到DatePicker之前从该月份减1。这是我把所有事情都设置好的一个烦恼。当你想比较你的数据库中的字符串和你作为字符串的日期时,只要确保你在SQLite的日期和时间函数中输入了字符串,以确保它们都能正常工作。希望我帮助:)学习代码的好运气。看起来你的行事很好。 – Andy 2012-08-04 17:56:19

+0

我实现了上面所做的一切。为了检索和修改日期,我从数据库中取出字符串,在每个“空间”处将其拆分为数组,然后使用“日”和“年”的适当部分。 '月'用于'if else'块中,每个月分配一个从0到11的值。我将所有3个部分解析为整数,并将它们设置在日历中。一段时间后,我将字符串分割为空格,然后在每个':'处分割该数组中的时间字符串,然后很容易获取hh和mm整数。修改我的帖子以协助其他看到此内容的人。 – Ronnie 2012-08-05 01:26:01