[英]Trying to get sum from Room database column
這是我在這里的第一個問題,我是編碼初學者,如果我的問題不是很清楚,請原諒我。
我已將工資存儲在名為“工資”的 Room 數據庫列中,數據類型為 double。 有不同日子的工資,我想在我的活動中顯示這些雙倍數字的總數。 如果嘗試了許多不同的方法來做到這一點,但我無法讓它在沒有不同錯誤的情況下工作。
如果我可以將該總和存儲到一個變量中,那將是理想的,這樣我就可以輕松使用它,並且可能會在必要時從中減去一些值。
我使用 Repository 和 ViewModel 來訪問我的數據庫,並使用 RecyclerView、Adapter 和 CardView 在我的 MainActivity 中顯示不同的數據。 我希望我不需要使用這些來訪問這個總和數,而是盡可能直接地訪問它。
這是我的@entity
@Entity (tableName = "shift_table")
public class Shift implements Serializable {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "date")
private String date;
@ColumnInfo(name = "start")
private String start;
@ColumnInfo(name = "end")
private String end;
@ColumnInfo (name = "hours")
private String hours;
@ColumnInfo (name = "wage")
private double wage;
public Shift(String date, String start, String end, String hours, double wage) {
this.date = date;
this.start = start;
this.end = end;
this.hours = hours;
this.wage = wage;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getDate() {
return date;
}
public String getStart() {
return start;
}
public String getEnd() {
return end;
}
public String getHours() {
return hours;
}
public double getWage() {
return wage;
}
}
這是我的@Dao
@Dao
public interface ShiftDao {
@Insert
void insert (Shift shift);
@Update
void update (Shift shift);
@Delete
void delete (Shift shift);
@Query("DELETE FROM shift_table")
void deleteAllShifts();
@Query("SELECT * FROM shift_table ORDER BY id DESC")
LiveData<List<Shift>> getAllShifts();
@Query("SELECT SUM(wage) FROM shift_table")
What here?
}
如何將 SUM 從工資列獲取到變量並在 TextView 中顯示?
在你的 DAO 中應該是這樣的:
@Query("SELECT SUM(" + "wage" + ") as wagesSum "+ " FROM " + "shift_table")
double getWageSum();
現在,有幾點建議:
將列名放入最終常量中,如下所示:
公共最終字符串 COLUMN_DATE_NAME = "日期"; @ColumnInfo(name = COLUMN_DATE_NAME) 私有字符串日期;
這樣,您可以更輕松地在 DAO 中靜態訪問常量,並且如果將來您可能想要更改該列的名稱,您只需在常量中更改它。 另外,請對表名執行相同的操作。 當您編寫可能的未來遷移時,這些常量也會為您提供幫助。
快樂編碼!
這是我的一些 kotlin 代碼,享受吧:)
道
@Query("SELECT SUM(column) FROM table")
fun getSum(): Int
存儲庫
private val mDao: Dao
init {
val database = getInstance(mApplication)
mDao = database.dao()
}
private class sumAsyncTask(private val mDao: Dao) : AsyncTask<Void, Void, Int>() {
protected override fun doInBackground(vararg voids: Void): Int {
return mDao.getSum()
}
}
fun getSum(): Int {
return sumAsyncTask(mDao).execute().get()
}
可能還有其他方法可以做到這一點,這就是我使用的。
PS: as for the Doubles, you might want to store them as Long / SQL Integer instead (see Create Room Entity for a Table which has a field with LONG datatype in Sqlite ) This can be done by simply multiplying by 100 (then you have美分,如果你的工資代表金錢)在存儲到數據庫之前
您可以像下面的示例一樣獲得雙列的總和。 雙列值的總和將存儲在BigDecimal
中。 有關更多詳細信息,您可以查看文檔。
@Query("SELECT SUM(column) FROM table")
LiveData<BigDecimal> getSum();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.