[英]Getting objects from Room database, and check for max wind at place for foregroundservice
I am working in android studios, where I've loaded a room database with surfspots.我在 android 工作室工作,在那里我加载了一个带有 surfspots 的房间数据库。 I would like to build a notifikation service(foregroundservice) that checks which place there is most wind.我想建立一个通知服务(前台服务)来检查哪个地方风最多。 When getting all the spots fro the DAO as a List, it says it can't run on the main thread.当从 DAO 获取所有点作为列表时,它说它不能在主线程上运行。 can someone help make a solution with LiveData?有人可以帮助使用 LiveData 制定解决方案吗?
DAO道
@Dao
public interface SurfSpotDAO {
@Query("SELECT * FROM surfSpot")
LiveData<List<SurfSpot>> getAllSpots();
// Get all spots from database
@Query("SELECT * FROM surfSpot")
LiveData<List<SurfSpot>> getAll();
// Get specific spot from database
@Query("SELECT * FROM surfSpot WHERE surfSpotID LIKE :spotID")
LiveData<SurfSpot> getSpot(int spotID);
// Add spot to database
@Insert(onConflict = OnConflictStrategy.IGNORE)
void addSpot(SurfSpot spot);
// Update spot information in database
@Update
void updateSpot(SurfSpot spot);
// Delete spot from database
@Delete
void delete(SurfSpot spot);
}
Repository存储库
public List<SurfSpot> getAllSpots() {
return db.surfSpotDAO().getAllSpots();
}
The method in Foregroundservice Foregroundservice中的方法
Repository repository; // Handle API calls via repository
public SurfSpot maxwindSpot = new SurfSpot();
List<SurfSpot> spots;
@RequiresApi(api = Build.VERSION_CODES.N)
private void getWind() {
spots = repository.getAllSpots();
maxwindSpot = Collections.max(spots, Comparator.comparingDouble(SurfSpot::getWindSpeed));
getRecommendation(maxwindSpot);
Solution 1 (Not recommended):解决方案1(不推荐):
Room.databaseBuilder(this, AppDatabase::class.java, "MyDatabase")
.allowMainThreadQueries() // this
.build()
Solution 2:解决方案2:
Use Kotlin Coroutines
.使用Kotlin Coroutines
。
Solution 3 (Deprecated): Use AsyncTask
in Java.解决方案 3(已弃用):在 Java 中使用AsyncTask
。
Solution 4: Use a separated Thread
.解决方案 4:使用单独的Thread
。
Solution 5: Use Executors
.解决方案 5:使用Executors
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.