房间数据库DAO使用int值查询到SUM()列并返回它...使用MVM模型

时间:2019-01-20 00:05:26

标签: java sqlite android-room

我正在使用android房间数据库构建一个应用程序。一切正常。我可以从数据库中插入,更新和删除。我试图将这些列加起来并在一个activity(UI)中返回它们的值。

我试图在DAO界面中添加一个查询以对列求和,然后在存储库中添加AsyncTask,但是我很困惑我是否应该为总计活动创建新的视图模型和适配器

实体:

@Entity(tableName = "note_table")
public class notetable {

    @PrimaryKey(autoGenerate = true)
    private int id;

    private String date;

    private int pay;

    private int miles;

    private int orders;

    private int expenses;

    public notetable(String date, int miles, int pay, int orders, int expenses) {

        this.date = date;
        this.pay = pay;
        this.miles = miles;
        this.orders = orders;
        this.expenses = expenses;
    }
}

DAO界面:

@Dao
public interface notedao {

    @Insert
    void insert(notetable note);

    @Update
    void update(notetable note);

    @Delete
    void delete(notetable note);

    @Query("DELETE FROM note_table")
    void deleteAllNotes();

    @Query("SELECT * FROM note_table ORDER BY date DESC")
    LiveData<List<notetable>> getAllNotes();

     @Query("SELECT SUM(pay) as totalpay FROM note_table") // this is where 
     I am stuck
int getPayTotal();

}

The activity in which I am trying to show the totals


public class DashActivity extends AppCompatActivity {
    private TextView totaldatecount, totalmiles, totalpay, totalorders, 
totalexpenses;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dash);
        totaldatecount = (TextView) findViewById(R.id.text_view_totaldays);
        totalmiles = (TextView) findViewById(R.id.text_view_totalmiles);
        totalpay = (TextView) findViewById(R.id.text_view_totalmoney);
        totalorders = (TextView) findViewById(R.id.text_view_totalorder);
        totalexpenses = (TextView) findViewById(R.id.text_view_totalexpense);

    }
}

Repository:
  private static class GetPayTotatlAsyncTask extends AsyncTask<Void, Void, 
     Void>{

    private notedao noteDao;

    private GetPayTotatlAsyncTask(notedao noteDao) {
        this.noteDao = noteDao;
    }
    @Override
    protected Void doInBackground(Void... voids) {
        noteDao.getPayTotal();
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

你必须返回不是“null”的值。

<块引用>

私有静态类 GetPayTotatlAsyncTask 扩展了 AsyncTask {

    private notedao noteDao;

    private GetPayTotatlAsyncTask(notedao noteDao) {
        this.noteDao = noteDao;
    }

    @Override
    protected Void doInBackground(Void... voids) {
        int total = noteDao.getPayTotal();
        return total;
    }
}

在活动类中:

<块引用>

int result = new GetPayTotatlAsyncTask.execute().get();
totalpay.setText(result);