Home > database >  how to fetch data from room Database kotlin
how to fetch data from room Database kotlin

Time:12-22

I m new in RoomDatabse. I have to fetch Data from Room database in offline mode. here is code

Json

[
 {"id": 1,
  "name": "Hero",
  "image": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg",
  "age": "23"}
]

Here is Model

class Actor() : ArrayList<ActorItem>()
@Entity(tableName = "actor",indices = arrayOf(Index(value= arrayOf("id"),unique = true)))
data class ActorItem(

    @PrimaryKey(autoGenerate = true)
    val id_:Int,
    @SerializedName("age")
    @ColumnInfo(name = "age")
    val age: String,
    @SerializedName("id")
    @ColumnInfo(name = "id")
    val id: Int,
    @SerializedName("image")
    @ColumnInfo(name="image")
    val image: String,
    @SerializedName("name")
    @ColumnInfo(name = "name")
    val name: String
)

Repository Class


class ReposetoryHelper(
    private val actorApi: ActorApi,
    private val databaseHelper: DatabaseHelper,
    private val applicationContext: Context)
{
    private val actorData = MutableLiveData<Actor>()
    val actors : LiveData<Actor>
    get() = actorData

    suspend fun getActor(){
        if(NetworkUtil.isInternetAvailable(applicationContext)){
            //fatch data from API while Online
            val result_ = actorApi.getActor()
            if (result_.body()!=null){
                databaseHelper.actorDao().addActor(result_.body()!!)
                actorData.postValue(result_.body())
            }
        }else{
                //fatch data from Database while Offline
            }
        }
    }

Dao Class

@Dao
interface ActorDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun addActor(actorItem: List<ActorItem>)

    @Query("SELECT * FROM actor")
    suspend fun getActor():List<ActorItem>
}

so While connected with network data come from API. but now how do i get Data From Database while i lost connection.

CodePudding user response:

Please use like this:

@Query("SELECT * FROM ActorItem")
suspend fun getActor():List<ActorItem>

Use ActorItem table as a model

actorData.postValue(databaseHelper.actorDao().getActor()) then you will not get the type mismatch error.

CodePudding user response:

you can try this way

@Query("SELECT * FROM actor")
fun getActor():LiveData<List<ActorItem>>

then you can try

 actorDao.getActor().observe(this, Observer<List<ActorItem>>() {
            @Override
            public void onChanged(List<ActorItem> actorItemList) {

            }
        })
  • Related