我有一项服务,可在每次找到新位置时将数据插入到Room数据库中。
@Override
public void onLocationUpdate(Location location) {
final Point point = new Point();
point.setTripId(0);
point.setDate(new Date());
point.setLatitude(location.getLatitude());
point.setLongitude(location.getLongitude());
Completable completable = Completable
.fromAction(() -> appDataBase.pointDao().insert(point));
}
但是由于某种原因,当我订阅主活动时,我没有在数据库中获取新值,它仅返回一次空列表:
appDataBase.pointDao().getAllByTripId(0)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(points -> Log.d("TripActivity", points.toString()));
这是我的道:
@Dao
public interface PointDao {
@Query("SELECT * FROM points WHERE tripId = :tripId")
Flowable<List<Point>> getAllByTripId(int tripId);
@Insert
void insert(Point point);
@Query("DELETE FROM points WHERE tripId = :tripId")
void deleteByTripId(int tripId);
}
我的实体:
@Entity(tableName = "points")
public class Point {
public static final int DEFAULT_TRIP_ID = 0;
@PrimaryKey(autoGenerate = true)
private int id;
private int tripId;
private double latitude;
private double longitude;
private Date date;
public Point() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTripId() {
return tripId;
}
public void setTripId(int tripId) {
this.tripId = tripId;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
RoomDatabase:
@Database(entities = {Point.class, Trip.class}, version = 1, exportSchema = false)
@TypeConverters({Converters.class})
public abstract class AppDataBase extends RoomDatabase {
public abstract TripDao tripDao();
public abstract PointDao pointDao();
}
这是我用Dagger注入的数据库结构。
@Provides
@Singleton
public AppDataBase provideAppDataBase(Context context) {
return Room.databaseBuilder(context, AppDataBase.class, "Trips").build();
}
我真的不知道我缺少什么。
答案 0 :(得分:3)
这是一个匕首问题。我使用了两个不同的appDataBase实例,这就是为什么flowable对插入没有反应的原因。我觉得自己是个白痴,但希望这可以帮助处于相同情况的其他人。
答案 1 :(得分:0)
Completable completable = Completable
.fromAction(() -> appDataBase.pointDao().insert(point));
您必须先订阅您的补充内容,然后它才能开始工作。