Dynamic Section Header Of RecyclerView Using Current Date&Time

后端 未结 4 1926
轮回少年
轮回少年 2021-02-08 07:46

I\'ll use RecyclerView for a section header

I want to create section header when i insert each Date & Time data in SQLite Database

I followed

4条回答
  •  猫巷女王i
    2021-02-08 08:42

    if I understand you correctly, your challenge is querying the SQLite db, group the records into dates, and display them in sections in the view.

    Take a look at this:

    public String formatDate(long dateTime) {
        String formatedDate;
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(dateTime);
        Date mDate = calendar.getTime();
        SimpleDateFormat sdf;
        sdf = new SimpleDateFormat("EEEE dd EEEE", new Locale("en"));
        formatedDate = sdf.format(mDate);
        return formatedDate;
    } 
    
    SQLiteDatabase db = this.getReadableDatabase(); 
    //select companies, order record by date-time created desc (or asc)
    Cursor cursor = db.query(Company.TABLE_NAME, null, null,
            null, null, null, DatabaseHelper.KEY_CREATED_AT + " DESC", null);
    String day="";
    ArrayList childList= new ArrayList();
    int index = 0;
    ArrayList sectionHeaders = new ArrayList<>();
    if (cursor.moveToFirst()){
          //assign the formatted current date to a variable
    
         day = formatDate(cursor.getString(cursor.getColumnIndex(DatabaseHelper.KEY_CREATED_AT)));
         String current_day = formatDate(cursor.getString(cursor.getColumnIndex(DatabaseHelper.KEY_CREATED_AT)));
         while(cursor.moveToNext()){
              current_day = formatDate(cursor.getString(cursor.getColumnIndex(DatabaseHelper.KEY_CREATED_AT)));
              childList.add(new Company(cursor.getColumnIndex(DatabaseHelper.KEY_COMPANY_NAME), getFromatDate(cursor.getString(cursor.getColumnIndex(DatabaseHelper.KEY_CREATED_AT))));
              //compare with day var
              if(!day.equals(current_day)) {
                 //We are beginning a new day, so add the previous days company to the sectioned list
                 sectionHeaders.add(new CompanySectionHeader(new ArrayList(childList), day, ++index));
                 day=current_day; //this is 
                 childList.clear();
              }
          }
    }
    cursor.close();
    db.close();
    //attach sectionHeaders to view here
    

    I hope it helps.

提交回复
热议问题