I am working in android studios, where I've loaded a room database with 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. can someone help make a solution with 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
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):
Room.databaseBuilder(this, AppDatabase::class.java, "MyDatabase")
.allowMainThreadQueries() // this
.build()
Solution 2:
Use Kotlin Coroutines
.
Solution 3 (Deprecated): Use AsyncTask
in Java.
Solution 4: Use a separated Thread
.
Solution 5: Use Executors
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.