iT邦幫忙

2021 iThome 鐵人賽

DAY 21
0
Mobile Development

android studio 30天學習筆記系列 第 21

android studio 30天學習筆記-day 21 -獲得日期

  • 分享至 

  • twitterImage
  •  

一般在使用資料庫新增資料的時候,都會看到新建資料的日期跟時間,今天會再sqllite上加入日期。

我是用新的資料庫跟資料表來新增資料表欄位,其餘欄位不變。

在SqlDataBaseHelper.java新增日期欄位

日期跟時間使用INTEGER類型建立

@Override
    public void onCreate(SQLiteDatabase db) {
        String SqlTable = "CREATE TABLE IF NOT EXISTS User (" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "user text not null," +
                "salary text not null," +
                "currentTime INTEGER not null" +
                ")";
        db.execSQL(SqlTable);
    }

MainActivity

取得日期的方法

public String getTodayTime() {
        //String dateformat = "yyyyMMdd"; 成果圖第一個日期顯示的格式
        
        String dateformat = "yyyy/MM/dd"; //日期的格式(第二個)
        Calendar mCal = Calendar.getInstance(); 
        SimpleDateFormat df = new SimpleDateFormat(dateformat);
        String today = df.format(mCal.getTime());
        return today;
    }

SimpleDateFormat處理Calendar跟String之間的轉換

更改資料

public void UpdateData(View view) {
        String user =name.getText().toString();
        String userSalary =salary.getText().toString();
        String dateTime =getTodayTime(); //取得日期
        if (!user.isEmpty() ||!userSalary.isEmpty()) {
            ContentValues contentValues = new ContentValues();
            contentValues.put("user", user);
            contentValues.put("salary", userSalary);
            contentValues.put("currentTime",dateTime);
            db.update(DataBaseTable, contentValues, "_id =" + 2,null );
            Toast.makeText(this,"更新完成",Toast.LENGTH_SHORT).show();
            dataList=showData();
        }
    }

新增資料

public void AddList(View view) {
        String user =name.getText().toString();
        String userSalary =salary.getText().toString();
        String dateTime = getTodayTime(); //取得日期
        if (!user.isEmpty() ||!userSalary.isEmpty()) {
            ContentValues contentValues = new ContentValues();
            contentValues.put("user", user);
            contentValues.put("salary", userSalary);
            contentValues.put("currentTime",dateTime);
            db.insert(DataBaseTable, null, contentValues);
            Toast.makeText(this,"新增完成",Toast.LENGTH_SHORT).show();
            dataList=showData();
        }
        else{
            Toast.makeText(this,"請填寫資料",Toast.LENGTH_SHORT).show();
        }
    }

SimpleDateFormat日期時間的格式範例
最後在RecyclerviewAdapter綁定的layout那裡新建一個TextVIew做顯示,這樣就完成了。
成果:
透過log看到新增上去的資料

https://ithelp.ithome.com.tw/upload/images/20210901/201389666f1UkQC9KJ.png


上一篇
android studio 30天學習筆記-day 20-SQLlite
下一篇
android studio 30天學習筆記 -day 22-Dagger 前言
系列文
android studio 30天學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言