My app is crashing and the only thing I know for sure is that the main problem is this line ->
val placesDao = (application as HotspotBucketApp).placesDb.placesDao()
can any one tell please me why is this happening.
private fun getPlaceList() {
val placesDao = (application as HotspotBucketApp).placesDb.placesDao()
lifecycleScope.launch {
placesDao.fetchAllPlaces().collect {
placeList = ArrayList(it)
}
if (placeList.isNotEmpty()) {
lastId = placeList[placeList.size - 1].id
}
}
}
class HotspotBucketApp: Application() {
val placesDb by lazy {
PlacesDatabase.getInstance(this)
}
}
@Dao
interface PlacesDao {
@Query("select * from `placesTable`")
fun fetchAllPlaces(): Flow<List<PlaceEntity>>
@Insert
suspend fun insert(placeEntity: PlaceEntity)
@Delete
suspend fun delete(placeEntity: PlaceEntity)
}
@Database(entities = [PlaceEntity::class], version = 1)
abstract class PlacesDatabase: RoomDatabase() {
abstract fun placesDao(): PlacesDao
companion object {
@Volatile
private var INSTANCE: PlacesDatabase? = null
private const val PLACES_DB_NAME = "place_database"
fun getInstance(context: Context): PlacesDatabase {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Room.databaseBuilder(context.applicationContext, PlacesDatabase::class.java, PLACES_DB_NAME)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
}
return instance
}
}
}
}
@Entity(tableName = "placesTable")
data class PlaceEntity(
@PrimaryKey
val id: Int,
val title: String,
val image: String,
val description: String,
val date: String,
val location: String,
val latitude: Double,
val longitude: Double
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding?.root)
setSupportActionBar(binding?.addPlacesToolBar)
if (Build.VERSION.SDK_INT >= 33) {
onBackInvokedDispatcher.registerOnBackInvokedCallback(
OnBackInvokedDispatcher.PRIORITY_DEFAULT
) {
finish()
}
} else {
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
finish()
}
})
}
getPlaceList()
binding?.fABAddPlaces?.setOnClickListener {
val intent = Intent(this, AddPlaceActivity::class.java)
intent.putExtra("lats_place_id", lastId)
startActivity(intent)
}
}