Search code examples
androidreal-time

Update activity data (Data from cumming form server) without refresh activity


I have a question please help me. I make an app in which on a activity i get data from server. I have an admin panel in which there is form, I fill form and save data in Database. My question is i want when i save or update any data in Database the app show the new data without refresh the activity like cricket score updates etc. Please give your suggestions.


Solution

  • It can be done using Room database.

    Databse class may look like this:

    open abstract class MDatabase : RoomDatabase() {
    abstract fun dataDAO(): DataDAO
    

    }

    The Dao interface may look like the below:

    @Dao interface DataDAO {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun saveData(dataEntity: DataEntity)
    
    @Query(SELECT_ALL_DATA)
    fun observeDB(): LiveData<Array<DataEntity>>
    

    }

    In the activity:

    database.dataDAO()
    .observeDB()
    .observe(this, Observer<Array<DataEntity>> {
       //Update UI
    })