Room Abstract Pojo

I'm creating for fun an android application that tracks the spendings. I'm using Room to persist the user's data and I have POJOs that show the daily/weekly/monthly summaries.

These classes are quite similar, thus I would like to have one abstract POJO that contains the fields and extensions of it that reformat to the correct format. Something like:

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,...
}

Here the extension:

public class WeekInformation extends PeriodInformation{

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

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

}

However, I get following error message for the WeekInformation Class:

error: Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).

So it seems that this is not possible in Room, thus I would be happy to get some suggestion how to not have to copy the same code too often.

thank you.

EDIT: I use following DAO code to aggregate to the POJO, the column calendarDate has following format "yyyy-MM-dd'T'HH:mm:ss.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 answer

  • answered 2018-06-24 11:12 Mikael Ohlson

    I'd think about how your data is structured. SQLite and Room by extension, can do summaries and counts for you, like any other SQL-based DB abstraction, so maybe just represent each spending entry instead.

    Below is a pseudo-code example, I haven't actually tried building this, but it should point you in the right direction.

    public class Spending {
        @ColumnInfo(name = "DateTime")
        private final Long timestamp;
        @ColumnInfo(name = "Expense")
        private Integer expense;
    
       public Spending(long epochTimestampUTC, float expense) {
           this.timestamp = epochTimestampUTC;
           this.expense = expense;
       }
    }
    

    and then in your Data Access Object (DAO) you would construct sums and counts for relevant periods.

    @Dao
    public interface MyDao {
        @Query("SELECT SUM(Expense) FROM spending WHERE DateTime > :startDate AND DateTime <= :endDate")
        public Float calculatePerioExpenses(final long startDate, final long endDate);
    
        @Query("SELECT COUNT(*) FROM spending WHERE DateTime > :startDate AND DateTime <= :endDate")
        public Integer calculatePeriodSpendingCount(final long startDate, final long endDate);
    
    }
    

  • Translate Pojo to JSON

    I do the documentation. In pdf, my object should look like json. I create a collection of objects:

    Arrays.asList(new CoefficientPerQuantityParameter(2, BigDecimal.valueOf(0.9)),
                  new CoefficientPerQuantityParameter(10, BigDecimal.valueOf(0.8)),
                  new CoefficientPerQuantityParameter(40, BigDecimal.valueOf(0.7))
    )
    

    CoefficientPerQuantityParameter looks like this

    public class CoefficientPerQuantityParameter {
        private Integer hour;
        private BigDecimal cost;
    }
    

    And I accept it in the xhtml file:

    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <link href="style.css" rel="stylesheet" type="text/css"/>
            <title>My document</title>
        </head>
        <body>
            <div>
                 <p th:text="${coefficientPerQuantityParameter}"/>
            </div>
        </body>
    </html>
    

    I need to see the result in the form of JSON. But I see something completely different:

    [CoefficientPerQuantityParameter
    (hour=2, cost=0.9),
    CoefficientPerQuantityParameter
    (hour=10, cost=0.8),
    CoefficientPerQuantityParameter
    (hour=40, cost=0.7)]
    

    How to get it?

    {"2": 0.9,  "10": 0.8,   "40": 0.7} 
    
  • How to access value of parent and child both class from pojo using databinding android

    My respone of pojo class is like:

    {
        "data": {
            "first_name": "test",
            "last_name": "test123",
            "email": "test@gmail.com",
            "user_id": "11"
        },
        "message": "login successfully.",
        "status": "success."
    }
    

    and i want access both parent and child class like message and email from above response. How can i get using single pojo..? Here i am facing null pointer exception.

    My code is:

    <data>
        <variable name="MyParent"
            type="com.package.ParentModel"/>
    
    </data>
    
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="@={MyParent.data.email}"
        android:id="@+id/et_email"/>
    

    how can get property of parent and child both class of same pojo..?

  • Android Room DB - use static variable from another class in query

    When I write a query in DAO class can I use a static variable from another class (or enum)? If it's possible, please tell me HOW?

    I mean something like this:

    public enum MessageState {
       NOTHING,
       PENDING,
       SEND
    }
    

    and in query statement in DAO class:

    @Query("SELECT * FROM message_db WHERE state = :MessageState.PENDING.ordinal()")
    
  • Calendar TypeConverter for Room (Kotlin)

    I am trying to persist a timestamp in my room database using the following TypeConverter:

    class Converters {
    
        @TypeConverter
        fun fromTimestamp(value: Long?): Calendar? {
    
            if(value == null) return null
    
            val cal = GregorianCalendar()
            cal.timeInMillis = value
            return cal
        }
    
        @TypeConverter
        fun toTimestamp(timestamp: Calendar?): Long? {
    
            if(timestamp == null) return null
    
            return timestamp.timeInMillis
        }
    }
    

    Two of my Entities include the following column :

    @ColumnInfo(name = "timestamp")
    val timestamp: Calendar?,
    

    But I get a compilation error upon trying to build the project - I had no issues when using the Date TypeConverter example from the developer reference guide.

    I am unable to see what the actual error is as I just get a bunch of databinding 'cannot find symbol' errors if there is something wrong with the code related to Room.

  • How to use android paging library for background Syncing?

    i want to set up a back ground sync in my app using paging and room. How can i achieve that?