Возвращает NullPointerException, когда я беру из DAO данные
Я пытаюсь задрать из DAO данные, которые перед этим берутся с API, а возвращает ошибку, когда я пытаюсь придать значение TextView из этой самой базы
ProfileDAO
@Dao
interface ProfileDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun upsert(profileResponseModel: ProfileResponseModel)
@Query("select * from profile_list where id = $PRIKEY_PROFILE")
fun getProfileInfo(): LiveData<ProfileModel>
В ApiNetworkDataSourseImpl
private val _downloadedProfile = MutableLiveData<ProfileResponseModel>()
override val downloadedProfile: LiveData<ProfileResponseModel>
get() = _downloadedProfile
override suspend fun fetchProfile(customPost: CustomPostModel) {
getException(PRIKEY_PROFILE, customPost)
}
override suspend fun getException(fetchId: Int, model: Any) {
try {
when (fetchId) {
PRIKEY_LOGIN -> {
val fetchLogin = apiService
.postLogin(model as LoginPostModel)
.await()
_downloadedLogin.postValue(fetchLogin)
}
PRIKEY_FEED -> {
val fetchFeed = apiService
.postFeed(model as CustomPostModel)
.await()
_downloadedFeed.postValue(fetchFeed)
}
PRIKEY_PROFILE -> {
val fetchedProfile = apiService
.postProfile(model as CustomPostModel)
.await()
_downloadedProfile.postValue(fetchedProfile)
}
В RepositoryImpl
class RepositoryImpl(
private val appPrefs: AppPreferences,
private val loginDAO: LoginDAO,
private val profileDAO: ProfileDAO,
private val feedDAO: FeedDAO,
private val apiNetworkDataSource: ApiNetworkDataSource
) : Repository {
init {
apiNetworkDataSource.apply {
downloadedProfile.observeForever { newProfile ->
presistFetchedProfile(newProfile)
}
}
}
override suspend fun getProfile(customPostModel: CustomPostModel): LiveData<out ProfileUnitSpecific> {
return withContext(Dispatchers.IO) {
initProfileData(customPostModel)
return@withContext profileDAO.getProfileInfo()
}
}
private suspend fun initProfileData(customPostModel: CustomPostModel) {
fetchProfile(customPostModel)
}
private suspend fun fetchProfile(customPostModel: CustomPostModel) {
apiNetworkDataSource.fetchProfile(customPostModel)
}
private fun presistFetchedProfile(fetchedProfile: ProfileResponseModel) {
GlobalScope.launch(Dispatchers.IO) {
profileDAO.upsert(fetchedProfile)
}
}
Через Debug я понял, что в сеть ходит и берёт данные корректно
Room таблица ответа сервера
const val PRIKEY_PROFILE = 1
@Entity(tableName = "profile_list")
data class ProfileResponseModel(
@Embedded(prefix = "profile_")
val `data`: ProfileDataResponseModel,
val status: Int,
val message: String
){
@PrimaryKey(autoGenerate = false)
var id: Int = PRIKEY_PROFILE
}
data ответа
data class ProfileDataResponseModel(
val uid: Int,
val name: String,
val surname: String,
val position: String,
val department: String,
val phone: String,
val email: String,
val contacts: String,
val home: String,
val password: String
)
Выставляю зависисмости таблиц
class ProfileModel(
@ColumnInfo(name = "profile_uid")
override val userId: Int,
@ColumnInfo(name = "profile_name")
override val userName: String,
@ColumnInfo(name = "profile_surname")
override val userSurname: String,
@ColumnInfo(name = "profile_position")
override val userPosition: String,
@ColumnInfo(name = "profile_department")
override val userDepartment: String,
@ColumnInfo(name = "profile_phone")
override val userPhone: String,
@ColumnInfo(name = "profile_email")
override val userEmail: String,
@ColumnInfo(name = "profile_contacts")
override val userContacts: String,
@ColumnInfo(name = "profile_home")
override val userHome: String,
@ColumnInfo(name = "profile_password")
override val userPassword: String
) : ProfileUnitSpecific
То что должно получится
interface ProfileUnitSpecific {
val userId: Int
val userName: String
val userSurname: String
val userPosition: String
val userDepartment: String
val userPhone: String
val userEmail: String
val userContacts: String
val userHome: String
val userPassword: String
}
Сама Database
@Database(
entities = [LoginResponseModel::class,
ProfileResponseModel::class,
FeedResponseModel::class],
version = 1
)
abstract class CounituAppDatabase : RoomDatabase() {
abstract fun loginDAO(): LoginDAO
abstract fun profileDAO(): ProfileDAO
abstract fun feedDAO(): FeedDAO
companion object{
@Volatile private var instanse: CounituAppDatabase? = null
private val LOCK = Any()
operator fun invoke(context: Context) = instanse
?: synchronized(LOCK){
instanse
?: buildDatabase(
context
).also { instanse = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext,
CounituAppDatabase::class.java, "counity.db")
.build()
}
}
Конечная ошибка
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String apportunity.counity.data.db.model.unitlocalized.profile.ProfileUnitSpecific.getUserName()' on a null object reference
Место ошибки profileName.Text = it.userName в Фрагменте
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this, viewModelFactoryUser)
.get(UserViewModel::class.java)
bindUI()
}
private fun bindUI() = launch{
val profileInfo = viewModel.profile.await()
profileInfo.observe(viewLifecycleOwner, Observer {
Log.e("PROFILE", "Try")
profileName.text = it.userName
})
}
Как исправить?