Reputation: 429
I want to query with multiple filters using room database. For example
@Query("SELECT SUM(total_amount) as total FROM settlement_table where date_and_time>=:fromDate and date_and_time<=:toDate and orderType=:orderType and user_id=:user_id")
fun getSettlementDataTotalAmountOrderTypeUserId(fromDate: Long, toDate: Long,orderType:Int?,user_id: String?): ModelSum
I have a situation when user_id
and orderType
is null. some time either one is null. But when I pass null value it return no data
How can I acheive filter with single query?
Upvotes: 0
Views: 1085
Reputation: 457
If you need to valid null then you need do some modifications.
@Entity(tableName = "settlement_table")
data class Settlement(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Long = 0,
@ColumnInfo(name = "user_id") val user_id: String? = "-1",
@ColumnInfo(name = "orderType") val longitude: Int? = -1,
@ColumnInfo(name = "total_amount") val total_amount: Int,
@ColumnInfo(name = "date_and_time") val date_and_time: Long
)
Table where you have set default values when you insert values as null. So, now your query will be
@Query("SELECT SUM(total_amount) as total FROM settlement_table where date_and_time>=:fromDate and date_and_time<=:toDate and orderType=:orderType and user_id=:user_id")
fun getSettlementDataTotalAmountOrderTypeUserId(
fromDate: Long,
toDate: Long,
orderType: Int? = -1,
user_id: String? = "-1"
): ModelSum
Here you can see we set default values while insert to -1 and while performing query also we using the same values if that orderType
& user_id
found null
EDIT
then there is simple thing you need to do , You need to create three method with same name with different params, like Method overloading. Method 1 : With Both not null
@Query("SELECT SUM(total_amount) as total FROM settlement_table where date_and_time>=:fromDate and date_and_time<=:toDate and orderType=:orderType and user_id=:user_id")
fun getSettlementDataTotalAmountOrderTypeUserId(
fromDate: Long,
toDate: Long,
orderType: Int,
user_id: String
): ModelSum
Method 2 : With orderType is null
@Query("SELECT SUM(total_amount) as total FROM settlement_table where date_and_time>=:fromDate and date_and_time<=:toDate and user_id=:user_id")
fun getSettlementDataTotalAmountOrderTypeUserId(
fromDate: Long,
toDate: Long,
user_id: String
): ModelSum
Method 2 : With user_id is null
@Query("SELECT SUM(total_amount) as total FROM settlement_table where date_and_time>=:fromDate and date_and_time<=:toDate and orderType=:orderType")
fun getSettlementDataTotalAmountOrderTypeUserId(
fromDate: Long,
toDate: Long,
orderType: Int
): ModelSum
So when calling this method you need make conditions
if(orderType!=null && user_id!=null) {
// Call method 1
}else if(user_id!=null) {
// Call method 2
}else if(orderType!=null) {
// Call method 3
}
Hope it will helps you with your issue
Upvotes: 1