Комната Абстракт Pojo - PullRequest
       28

Комната Абстракт Pojo

0 голосов
/ 24 июня 2018

Я создаю для развлечения приложение для Android, которое отслеживает расходы.Я использую Room для сохранения данных пользователя, и у меня есть POJO, которые показывают ежедневные / еженедельные / ежемесячные сводки.

Эти классы очень похожи, поэтому я хотел бы иметь один абстрактный объект POJO, содержащий его поля и расширения, которые переформатируются в правильный формат.Что-то вроде:

public abstract class PeriodInformation {

PeriodInformation(@NonNull Calendar mCalendar, Integer mPeriodSpendingCount, Float mPeriodSpendingSum) {
    this.mCalendar = mCalendar;
    this.mPeriodSpendingCount = mPeriodSpendingCount;
    this.mPeriodSpendingSum = mPeriodSpendingSum;
}

@ColumnInfo(name = "DateTime")
private final Calendar mCalendar;
@ColumnInfo(name = "SpendingCount")
private Integer mPeriodSpendingCount;
@ColumnInfo(name = "SpendingSum")
private Float mPeriodSpendingSum;

// Some other code, e.g., getters, equal override,...
}

Здесь расширение:

public class WeekInformation extends PeriodInformation{

public WeekInformation(@NonNull Calendar mCalendar, Integer mPeriodSpendingCount, Float mMonthSpendingSum) {
    super(mCalendar, mPeriodSpendingCount, mMonthSpendingSum);
}

@Override
public String getPeriodRepresentation() {
    //return representation;
}

}

Однако я получаю следующее сообщение об ошибке для класса WeekInformation:

error: Entities иУ Pojos должен быть публичный конструктор.У вас может быть пустой конструктор или конструктор, параметры которого соответствуют полям (по имени и типу).

Так что кажется, что это невозможно в комнате, поэтому я был бы рад получить некоторые предложениякак не нужно копировать один и тот же код слишком часто.

спасибо.

РЕДАКТИРОВАТЬ: я использую следующий код DAO для агрегирования в POJO, столбец calendarDate имеет следующий формат "гггг-ММ-дд'Т'ЧЧ: мм: сс.SSSXXX":

@Query("SELECT date(datetime(calendarDate)) AS 'DateTime', count(uID) AS 'SpendingCount', sum(value)  AS 'SpendingSum' from spending GROUP BY date(datetime(calendarDate))")
LiveData<List<DayInformation>> loadDayInformation();

1 Ответ

0 голосов
/ 24 июня 2018

Я смог сделать эту работу для меня, используя встроенную аннотацию, позволяющую прямой доступ к полям встроенного типа данных.

public class DayInformation {

    @Embedded
    public PeriodInformation periodInformation;

    @Override
    public String toString() {
        return "DayInformation{" +
           "periodInformation=" + periodInformation +
           '}';
    }
}

и

public class PeriodInformation {

    PeriodInformation(Calendar timestamp,
                      int periodSpendingCount,
                      float periodSpendingSum) {
        this.timestamp = timestamp;
        this.periodSpendingCount = periodSpendingCount;
        this.periodSpendingSum = periodSpendingSum;
    }

    @ColumnInfo(name = "DateTime")
    public final Calendar timestamp;
    @ColumnInfo(name = "SpendingCount")
    public Integer periodSpendingCount;
    @ColumnInfo(name = "SpendingSum")
    public Float periodSpendingSum;

    @Override
    public String toString() {
        final DateFormat dateInstance = SimpleDateFormat.getDateInstance();
        String date = timestamp == null ? "null" : dateInstance.format(timestamp.getTime());
        return "PeriodInformation{" +
               "timestamp='" + date + '\'' +
               ", periodSpendingCount=" + periodSpendingCount +
               ", periodSpendingSum=" + periodSpendingSum +
               '}';
    }
}

плюс

@Entity
public class Spending {
    @PrimaryKey(autoGenerate = true)
    public int uid;

    @ColumnInfo(name = "calendarDate")
    public Calendar timestamp;

    @ColumnInfo(name = "value")
    public float value;

    public Spending(@NonNull Calendar timestamp, float value) {
        this.timestamp = timestamp;
        this.value = value;
    }

    @Override
    public String toString() {
        final DateFormat dateInstance = SimpleDateFormat.getDateInstance();
        String date = timestamp == null ? "null" : dateInstance.format(timestamp.getTime());


        return "Spending{" +
               "uid=" + uid +
               ", timestamp='" + date + '\'' +
               ", value=" + value +
               '}';
    }
}

и DAO

@Dao
public interface SpendingDao {

    @Insert
    void insertAll(Spending... spendings);

    @Query("SELECT * FROM spending")
    LiveData<List<Spending>> findAll();

    @Query("SELECT calendarDate AS 'DateTime', count(uID) AS 'SpendingCount', sum(value)  AS 'SpendingSum' from spending GROUP BY date(datetime(calendarDate))")
    LiveData<List<DayInformation>> loadDayInformation();
}

дает следующий вывод

aggregated data is 
DayInformation{periodInformation=PeriodInformation{timestamp='Jun 26, 2018', periodSpendingCount=8, periodSpendingSum=184.0}}
spending data is Spending{uid=1, timestamp='Jun 26, 2018', value=23.0}
spending data is Spending{uid=2, timestamp='Jun 26, 2018', value=23.0}
spending data is Spending{uid=3, timestamp='Jun 26, 2018', value=23.0}
spending data is Spending{uid=4, timestamp='Jun 26, 2018', value=23.0}
spending data is Spending{uid=5, timestamp='Jun 26, 2018', value=23.0}
spending data is Spending{uid=6, timestamp='Jun 26, 2018', value=23.0}
spending data is Spending{uid=7, timestamp='Jun 26, 2018', value=23.0}
spending data is Spending{uid=8, timestamp='Jun 26, 2018', value=23.0}
...