按时间和日期存储,检索和排序记录

时间:2012-08-04 05:35:51

标签: android sqlite android-datepicker

我想我可能在一篇文章中要求太多,所以让我知道我是否应该将其分解为日期和时间的单独问题,但在数据库中使用日期和时间让我完全陷入困境。我已经研究了各种方法(字符串,juliandates,unix等),所有这些都让我更加困惑。为了提供一些上下文,用户通过填写​​表单来添加记录。表单有2个按钮,一个打开带有日期选择器的片段,另一个打开带有timepicker的片段。选择的日期和时间显示为按钮文本。另一个按钮将表单详细信息保存到数据库中。

接下来,我有一个listview活动,显示当前的所有记录,但我最终想要一个datepicker片段的按钮,以便只显示具有特定日期的记录。然后按时间顺序列出这些记录。 (我想我可以在下一段解决后自己弄清楚这一段。)

单击列表视图中的一个记录将打开一个与原始表单(创建记录的位置)具有相同外观的活动,并使用该记录中的所有信息填充该活动。然后,用户可以选择删除记录,或修改记录中的字段并保存(更新)记录。此表单还应包含日期和时间按钮,以便这些也可以更改,因此选择器应设置为此活动中先前保存的日期/时间。

我需要帮助的是,存储日期和时间的最佳方法,然后在编辑表单中检索和编辑它,包括将其格式化为特定方法以显示为按钮文本(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(我的数据库帮助程序类):

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.

2 个答案:

答案 0 :(得分:1)

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

编辑:

我还做了一些额外的挖掘,因为我注意到我的应用程序实际上将日期和时间存储为INTEGER值,请查看SQLite中的不同data types,但更重要的是,第1.2节关于日期和时间数据类型。因此将它们保持为TEXTINTEGER是好的,只需要保持一致。

答案 1 :(得分: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");
}
}