将 EditText 中的日期 (MM-dd-yyyy) 格式化为 (yyyy-MM-dd) 并将其写入 sqlite

发布于 2024-12-03 15:40:01 字数 8265 浏览 0 评论 0原文

将 EditText 中的日期格式化为西班牙语格式(MM-dd-yyyy),并在 sqlite 数据库中以英语格式(yyyy-MM-dd)重写。

这是我的适配器代码:

public class AuxGlucDbAdapter {

public static final String KEY_IDPACIENTE = "IdPaciente";
public static final String KEY_FECHA = "Fecha";
public static final String KEY_EVE1 = "Eve1";
public static final String KEY_EVE2 = "Eve2";
public static final String KEY_EVE3 = "Eve3";
public static final String KEY_EVE4 = "Eve4";  
public static final String KEY_EVE5 = "Eve5";
public static final String KEY_EVE6 = "Eve6";
public static final String KEY_EVE7 = "Eve7";
public static final String KEY_ID = "_id";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(KEY_FECHA);
private static final String TAG = "AuxGlucDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;


private static final String DATABASE_CREATE =
    "create table AuxGluc (_id integer primary key autoincrement, "
    + "IdPaciente numeric not null, Fecha datetime not null, Eve1 numeric not null, Eve2 numeric not null, Eve3 numeric not null, Eve4 numeric not null, Eve5 numeric not null, Eve6 numeric not null, Eve7 numeric not null);";

private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "AuxGluc";
private static final int DATABASE_VERSION = 2;

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS AuxGluc");
        onCreate(db);
    }
}

public AuxGlucDbAdapter(Context ctx) {
    this.mCtx = ctx;
}

public AuxGlucDbAdapter open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    mDbHelper.close();
}

public long createNote(String IdPaciente, String Fecha, String Eve1, String Eve2, String Eve3, String Eve4, String Eve5, String Eve6, String Eve7) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_IDPACIENTE, IdPaciente);
    initialValues.put(KEY_FECHA, Fecha);
    initialValues.put(KEY_EVE1, Eve1);
    initialValues.put(KEY_EVE2, Eve2);
    initialValues.put(KEY_EVE3, Eve3);
    initialValues.put(KEY_EVE4, Eve4);
    initialValues.put(KEY_EVE5, Eve5);
    initialValues.put(KEY_EVE6, Eve6);
    initialValues.put(KEY_EVE7, Eve7);

    return mDb.insert(DATABASE_TABLE, null, initialValues);
}

public boolean deleteNote(long Id) {

    return mDb.delete(DATABASE_TABLE, KEY_ID + "=" + Id, null) > 0;
}

public Cursor fetchAllNotes() {

    return mDb.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_IDPACIENTE, KEY_FECHA,
            KEY_EVE1, KEY_EVE2, KEY_EVE3, KEY_EVE4, KEY_EVE5, KEY_EVE6, KEY_EVE7}, null, null, null, null, null, null);
}

public Cursor fetchNote(long Id) throws SQLException {

    Cursor mCursor =

        mDb.query(true, DATABASE_TABLE, new String[] {KEY_ID, KEY_IDPACIENTE,
                KEY_FECHA, KEY_EVE1, KEY_EVE2, KEY_EVE3, KEY_EVE4, KEY_EVE5, KEY_EVE6, KEY_EVE7}, KEY_ID + "=" + Id, null,
                null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

public boolean updateNote(long Id, String IdPaciente, String Fecha, String Eve1, String Eve2, String Eve3, String Eve4, String Eve5, String Eve6, String Eve7) {
    ContentValues args = new ContentValues();
    args.put(KEY_IDPACIENTE, IdPaciente);
    args.put(KEY_FECHA, Fecha);
    args.put(KEY_EVE1, Eve1);
    args.put(KEY_EVE2, Eve2);
    args.put(KEY_EVE3, Eve3);     
    args.put(KEY_EVE4, Eve4);   
    args.put(KEY_EVE5, Eve5); 
    args.put(KEY_EVE6, Eve6); 
    args.put(KEY_EVE7, Eve7); 

    return mDb.update(DATABASE_TABLE, args, KEY_ID + "=" + Id, null) > 0;
}
}

还有其他代码:

public class NoteEdit extends Activity {

private EditText mIdPacienteText;
private EditText mFechaText;
private EditText mEve1Text;
private EditText mEve2Text;
private EditText mEve3Text;
private EditText mEve4Text;
private EditText mEve5Text;
private EditText mEve6Text;
private EditText mEve7Text;
private Long mId;
private AuxGlucDbAdapter mDbHelper;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mDbHelper = new AuxGlucDbAdapter(this);
    mDbHelper.open();

    setContentView(R.layout.note_edit);
    setTitle(R.string.edit_note);

    mIdPacienteText = (EditText) findViewById(R.id.IdPaciente);
    mFechaText = (EditText) findViewById(R.id.Fecha);
    mEve1Text = (EditText) findViewById(R.id.Eve1);
    mEve2Text = (EditText) findViewById(R.id.Eve2);
    mEve3Text = (EditText) findViewById(R.id.Eve3);
    mEve4Text = (EditText) findViewById(R.id.Eve4);
    mEve5Text = (EditText) findViewById(R.id.Eve5);
    mEve6Text = (EditText) findViewById(R.id.Eve6);
    mEve7Text = (EditText) findViewById(R.id.Eve7);

    Button confirmButton = (Button) findViewById(R.id.confirm);

    mId = (savedInstanceState == null) ? null :
        (Long) savedInstanceState.getSerializable(AuxGlucDbAdapter.KEY_ID);
    if (mId == null) {
        Bundle extras = getIntent().getExtras();
        mId = extras != null ? extras.getLong(AuxGlucDbAdapter.KEY_ID)
                                : null;
    }

    populateFields();

    confirmButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            setResult(RESULT_OK);
            finish();
        }

    });
}

private void populateFields() {
    if (mId != null) {
        Cursor note = mDbHelper.fetchNote(mId);
        startManagingCursor(note);
        mIdPacienteText.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_IDPACIENTE)));
        mFechaText.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_FECHA)));
        mEve1Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE1)));
        mEve2Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE2)));
        mEve3Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE3)));
        mEve4Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE4)));
        mEve5Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE5)));
        mEve6Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE6)));
        mEve7Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE7)));

    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveState();
    outState.putSerializable(AuxGlucDbAdapter.KEY_ID, mId);
}

@Override
protected void onPause() {
    super.onPause();
    saveState();
}

@Override
protected void onResume() {
    super.onResume();
    populateFields();
}

private void saveState() {
    String IdPaciente = mIdPacienteText.getText().toString();
    String Fecha = mFechaText.getText().toString();
    String Eve1 = mEve1Text.getText().toString();
    String Eve2 = mEve2Text.getText().toString();
    String Eve3 = mEve3Text.getText().toString();
    String Eve4 = mEve4Text.getText().toString();
    String Eve5 = mEve5Text.getText().toString();
    String Eve6 = mEve6Text.getText().toString();
    String Eve7 = mEve7Text.getText().toString();

    if (mId == null) {
        long Id = mDbHelper.createNote(IdPaciente, Fecha, Eve1, Eve2, Eve3, Eve4, Eve5, Eve6, Eve7);
        if (Id > 0) {
            mId = Id;
        }
    } else {
        mDbHelper.updateNote(mId, IdPaciente, Fecha, Eve1, Eve2, Eve3, Eve4, Eve5, Eve6, Eve7);
    }
}

}

Format date in the EditText to be written in Spanish format (MM-dd-yyyy) and rewrite it in English format (yyyy-MM-dd) in the sqlite database.

Here is my code of adapter:

public class AuxGlucDbAdapter {

public static final String KEY_IDPACIENTE = "IdPaciente";
public static final String KEY_FECHA = "Fecha";
public static final String KEY_EVE1 = "Eve1";
public static final String KEY_EVE2 = "Eve2";
public static final String KEY_EVE3 = "Eve3";
public static final String KEY_EVE4 = "Eve4";  
public static final String KEY_EVE5 = "Eve5";
public static final String KEY_EVE6 = "Eve6";
public static final String KEY_EVE7 = "Eve7";
public static final String KEY_ID = "_id";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(KEY_FECHA);
private static final String TAG = "AuxGlucDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;


private static final String DATABASE_CREATE =
    "create table AuxGluc (_id integer primary key autoincrement, "
    + "IdPaciente numeric not null, Fecha datetime not null, Eve1 numeric not null, Eve2 numeric not null, Eve3 numeric not null, Eve4 numeric not null, Eve5 numeric not null, Eve6 numeric not null, Eve7 numeric not null);";

private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "AuxGluc";
private static final int DATABASE_VERSION = 2;

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS AuxGluc");
        onCreate(db);
    }
}

public AuxGlucDbAdapter(Context ctx) {
    this.mCtx = ctx;
}

public AuxGlucDbAdapter open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    mDbHelper.close();
}

public long createNote(String IdPaciente, String Fecha, String Eve1, String Eve2, String Eve3, String Eve4, String Eve5, String Eve6, String Eve7) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_IDPACIENTE, IdPaciente);
    initialValues.put(KEY_FECHA, Fecha);
    initialValues.put(KEY_EVE1, Eve1);
    initialValues.put(KEY_EVE2, Eve2);
    initialValues.put(KEY_EVE3, Eve3);
    initialValues.put(KEY_EVE4, Eve4);
    initialValues.put(KEY_EVE5, Eve5);
    initialValues.put(KEY_EVE6, Eve6);
    initialValues.put(KEY_EVE7, Eve7);

    return mDb.insert(DATABASE_TABLE, null, initialValues);
}

public boolean deleteNote(long Id) {

    return mDb.delete(DATABASE_TABLE, KEY_ID + "=" + Id, null) > 0;
}

public Cursor fetchAllNotes() {

    return mDb.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_IDPACIENTE, KEY_FECHA,
            KEY_EVE1, KEY_EVE2, KEY_EVE3, KEY_EVE4, KEY_EVE5, KEY_EVE6, KEY_EVE7}, null, null, null, null, null, null);
}

public Cursor fetchNote(long Id) throws SQLException {

    Cursor mCursor =

        mDb.query(true, DATABASE_TABLE, new String[] {KEY_ID, KEY_IDPACIENTE,
                KEY_FECHA, KEY_EVE1, KEY_EVE2, KEY_EVE3, KEY_EVE4, KEY_EVE5, KEY_EVE6, KEY_EVE7}, KEY_ID + "=" + Id, null,
                null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}

public boolean updateNote(long Id, String IdPaciente, String Fecha, String Eve1, String Eve2, String Eve3, String Eve4, String Eve5, String Eve6, String Eve7) {
    ContentValues args = new ContentValues();
    args.put(KEY_IDPACIENTE, IdPaciente);
    args.put(KEY_FECHA, Fecha);
    args.put(KEY_EVE1, Eve1);
    args.put(KEY_EVE2, Eve2);
    args.put(KEY_EVE3, Eve3);     
    args.put(KEY_EVE4, Eve4);   
    args.put(KEY_EVE5, Eve5); 
    args.put(KEY_EVE6, Eve6); 
    args.put(KEY_EVE7, Eve7); 

    return mDb.update(DATABASE_TABLE, args, KEY_ID + "=" + Id, null) > 0;
}
}

And here other code:

public class NoteEdit extends Activity {

private EditText mIdPacienteText;
private EditText mFechaText;
private EditText mEve1Text;
private EditText mEve2Text;
private EditText mEve3Text;
private EditText mEve4Text;
private EditText mEve5Text;
private EditText mEve6Text;
private EditText mEve7Text;
private Long mId;
private AuxGlucDbAdapter mDbHelper;

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mDbHelper = new AuxGlucDbAdapter(this);
    mDbHelper.open();

    setContentView(R.layout.note_edit);
    setTitle(R.string.edit_note);

    mIdPacienteText = (EditText) findViewById(R.id.IdPaciente);
    mFechaText = (EditText) findViewById(R.id.Fecha);
    mEve1Text = (EditText) findViewById(R.id.Eve1);
    mEve2Text = (EditText) findViewById(R.id.Eve2);
    mEve3Text = (EditText) findViewById(R.id.Eve3);
    mEve4Text = (EditText) findViewById(R.id.Eve4);
    mEve5Text = (EditText) findViewById(R.id.Eve5);
    mEve6Text = (EditText) findViewById(R.id.Eve6);
    mEve7Text = (EditText) findViewById(R.id.Eve7);

    Button confirmButton = (Button) findViewById(R.id.confirm);

    mId = (savedInstanceState == null) ? null :
        (Long) savedInstanceState.getSerializable(AuxGlucDbAdapter.KEY_ID);
    if (mId == null) {
        Bundle extras = getIntent().getExtras();
        mId = extras != null ? extras.getLong(AuxGlucDbAdapter.KEY_ID)
                                : null;
    }

    populateFields();

    confirmButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            setResult(RESULT_OK);
            finish();
        }

    });
}

private void populateFields() {
    if (mId != null) {
        Cursor note = mDbHelper.fetchNote(mId);
        startManagingCursor(note);
        mIdPacienteText.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_IDPACIENTE)));
        mFechaText.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_FECHA)));
        mEve1Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE1)));
        mEve2Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE2)));
        mEve3Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE3)));
        mEve4Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE4)));
        mEve5Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE5)));
        mEve6Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE6)));
        mEve7Text.setText(note.getString(
                note.getColumnIndexOrThrow(AuxGlucDbAdapter.KEY_EVE7)));

    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveState();
    outState.putSerializable(AuxGlucDbAdapter.KEY_ID, mId);
}

@Override
protected void onPause() {
    super.onPause();
    saveState();
}

@Override
protected void onResume() {
    super.onResume();
    populateFields();
}

private void saveState() {
    String IdPaciente = mIdPacienteText.getText().toString();
    String Fecha = mFechaText.getText().toString();
    String Eve1 = mEve1Text.getText().toString();
    String Eve2 = mEve2Text.getText().toString();
    String Eve3 = mEve3Text.getText().toString();
    String Eve4 = mEve4Text.getText().toString();
    String Eve5 = mEve5Text.getText().toString();
    String Eve6 = mEve6Text.getText().toString();
    String Eve7 = mEve7Text.getText().toString();

    if (mId == null) {
        long Id = mDbHelper.createNote(IdPaciente, Fecha, Eve1, Eve2, Eve3, Eve4, Eve5, Eve6, Eve7);
        if (Id > 0) {
            mId = Id;
        }
    } else {
        mDbHelper.updateNote(mId, IdPaciente, Fecha, Eve1, Eve2, Eve3, Eve4, Eve5, Eve6, Eve7);
    }
}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝海 2024-12-10 15:40:01

Sqlite 没有“日期时间”类型。您最好存储 Unix 时间戳(我认为 date.getTime() ) - 以毫秒为单位,然后使用 sqlite 中的 date()、time() 和 strftime() 函数将 sqlite 中的时间戳转换为您喜欢的任何内容(参见下面的链接)。

请参阅链接了解 sqlite 数据类型。

请参阅链接了解如何在 sqlite 中设置日期格式。

另请参阅这个问题以获得更多帮助。

编辑:回答您的问题(来自上面的链接):

SQLite 没有为存储日期预留的存储类
和/或时间。相反,SQLite 的内置日期和时间函数
能够将日期和时间存储为 TEXT、REAL 或 INTEGER
值:

TEXT 作为 ISO8601 字符串(“YYYY-MM-DD HH:MM:SS.SSS”)。真实如朱利安
天数,自 11 月格林威治中午以来的天数
根据公历,公元前 4714 年 24 日。整数
作为 Unix 时间,自 1970-01-01 00:00:00 UTC 以来的秒数。
应用程序可以选择将日期和时间存储在其中任何一个中
格式并使用内置日期和格式在格式之间自由转换
时间函数。

因此,当您存储 yyyy-MM-dd 时,它实际上是将其存储为文本字段(或字符串)。当你把它拉出来时,它会像你存储它一样出现,但它是一个字符串,如果不首先在 Java 中解析,就不能将其作为日期进行操作。即使使用我的方法,您仍然必须解析日期,但您可以按照您喜欢的方式格式化查询中的日期(yyyy-MM-dd 或 MM-dd-yyyy)。

在 sqlite 中将日期以毫秒为单位存储为 INTEGER 的优点是您现在可以在查询中对日期进行排序。

编辑:

示例:

您的数据库创建字符串如下所示:

private static final String DATABASE_CREATE =
    "create table AuxGluc (_id integer primary key autoincrement, "
    + "IdPaciente numeric not null, Fecha integer not null, Eve1 numeric not null, Eve2 numeric not null, Eve3 numeric not null, Eve4 numeric not null, Eve5 numeric not null, Eve6 numeric not null, Eve7 numeric not null);";

现在,当您保存日期时,您可以使用 Android Calendar 类,并调用 myCalendar.getTimeInMillis() 获取整数值。所以你的 createNode 签名将如下所示:

public long createNote(String IdPaciente, int Fecha, String Eve1, String Eve2, String Eve3, String Eve4, String Eve5, String Eve6, String Eve7) {...}

Sqlite does not have a "datetime" type. You would be better off storing the Unix Timestamp (date.getTime() I think) - which is in milliseconds, and converting that in sqlite to whatever you like using the date(), time(), and strftime() functions in sqlite (see links below).

Please see this link to learn about sqlite data types.

See this link to see how to format dates in sqlite.

Also see this, and this question for more help.

EDIT: In response to your question (from the link above):

SQLite does not have a storage class set aside for storing dates
and/or times. Instead, the built-in Date And Time Functions of SQLite
are capable of storing dates and times as TEXT, REAL, or INTEGER
values:

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). REAL as Julian
day numbers, the number of days since noon in Greenwich on November
24, 4714 B.C. according to the proleptic Gregorian calendar. INTEGER
as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these
formats and freely convert between formats using the built-in date and
time functions.

So when you store yyyy-MM-dd it is actually storing it as a TEXT field (or string). When you pull it out it comes out just as you stored it, but it is a string and cannot be manipulated as a date without parsing in Java first. Even with my method you still have to parse the date out, but you can format dates in your queries however you like (yyyy-MM-dd or MM-dd-yyyy).

The advantage of storing the date in milliseconds as an INTEGER in sqlite is that you can now sort your dates in your query.

EDIT:

Example:

Your database creation string would look like the following:

private static final String DATABASE_CREATE =
    "create table AuxGluc (_id integer primary key autoincrement, "
    + "IdPaciente numeric not null, Fecha integer not null, Eve1 numeric not null, Eve2 numeric not null, Eve3 numeric not null, Eve4 numeric not null, Eve5 numeric not null, Eve6 numeric not null, Eve7 numeric not null);";

Now when you save a date, you could use Androids Calendar class, and call myCalendar.getTimeInMillis() to get the integer value. So your createNode signature would look like this:

public long createNote(String IdPaciente, int Fecha, String Eve1, String Eve2, String Eve3, String Eve4, String Eve5, String Eve6, String Eve7) {...}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文