Insert to room in service not updating LiveData in activity

情到浓时终转凉″ 提交于 2019-12-11 07:47:25

问题


I'm using room to communicate data fetched by a foreground Location service with the an activity. The service connects to the viewmodel and does insert data, the activity however does not receive updated LiveData from the viewmodel, it is however able to fetch a LiveData> object at the begining, with accurate size when restarting the app. What am I missing here? I need to insert new data into the db, so if I do need to use MutableLiveData in the service and postValue, then I would have to post the entire list everytime...

Activity.java


@Override
protected void onCreate( Bundle savedInstanceState ) {
    super.onCreate( savedInstanceState );

    setContentView( R.layout.track_activity );

    mViewModel = ViewModelProviders.of( this ).get( ViewModel.class );

    mViewModel.getAllData().observe( this, ( @Nullable final <List<eData>> data ) -> {

        if ( data!= null )
            Log.d("DATACOUNT", String.valueOf(data.size()) );

    } );
}

Service.java

@Override
public void onCreate() {
    super.onCreate();

    AppDatabase mDB = AppDatabase.getDatabase( this.getApplication() );
    mDataDao = mDB.dataDao();

    mExecutor = Executors.newSingleThreadExecutor();

}

...

private void receiveLocation( LocationResult locationResult ) {

    ...
    mExecutor.execute( () -> mDataDao.insertData( new eData( ... ) ) );

}

DataDao.java

@Dao
public interface DataDao {

    @Query( "SELECT * FROM eData" )
    LiveData<List<eData>> getAllData();

    @Insert
    long insertData( eData data );
}

AppDatabase.java

@Database(entities = { eData.class }, version = 1 )
public abstract class AppDatabase extends RoomDatabase {

    public abstract DataDao dataDao();

    private static AppDatabase INSTANCE;

    public static AppDatabase getDatabase( final Context context ) {
        if ( INSTANCE == null ) {
            synchronized ( AppDatabase.class ) {
                if ( INSTANCE == null ) {
                    INSTANCE = Room.databaseBuilder( context.getApplicationContext(),
                            AppDatabase.class, "locationapp" )
                                       .build();
                }
            }
        }
        return INSTANCE;
    }

The Repository and Database are Singletons. But somewhow the LiveData observed in my activity does not update when inserting entities in the service, which it does insert into the database, as when I restart the app, the count goes up.


回答1:


Ended up not using room in the service at all. One, I didn't know whether it would be faster, and two, it uses less memory if I just stick with the activity and only create ViewModel and ExecutorService once.



来源:https://stackoverflow.com/questions/57495102/insert-to-room-in-service-not-updating-livedata-in-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!