我正在尝试添加数据到firestore。我也想这样做使用匕首。但我一直得到这个错误。你能帮助我吗......
默认FirebaseApp未在此进程com.example.vvvv中初始化。请确保首先调用FirebaseApp.initializeApp(Context)。
Firestore存储库
class FirestoreRepository @Inject constructor(private val usersRef:
CollectionReference) {
fun saveSearchResults(userEntities: List<UserEntity>) {
usersRef.add(userEntities).addOnCompleteListener { task ->
when (task.isSuccessful) {
true -> Log.d(ContentValues.TAG, "added:success")
false -> Log.d(ContentValues.TAG, "added:unsuccess")
}
}
}
}
视图模型
@HiltViewModel
class UserListViewModel @Inject constructor(private val repository: RoomRepository, private
val firestoreRepository: FirestoreRepository) :
ViewModel() {
private val _users = MutableLiveData<List<User>>()
val users: LiveData<List<User>>
get() = _users
var userData: MutableLiveData<List<User>> = MutableLiveData()
fun userSearch(term: String) {
viewModelScope.launch {
loadFromCache(term)
val getPropertiesDeferred =
GithubApi.retrofitService.searchUser(term)
try {
val userEntities: MutableList<UserEntity> = mutableListOf()
val result = getPropertiesDeferred.body()
_users.value = result?.users
result?.users?.forEach {
userEntities.add(
UserEntity(
term = term,
login = it.login,
avatar_url = it.avatar_url
)
)
}
clearSearchResults(term)
updateSearchResults(userEntities, term)
firestoreRepository.saveSearchResults(userEntities) //save
data with firebase
} catch (e: Exception) {
Log.e("userListErr", e.message.toString())
}
}
}
private fun updateSearchResults(userEntities: List<UserEntity>, term:
String) {
viewModelScope.launch(Dispatchers.IO) {
repository.insertSearchResults(userEntities)
loadFromCache(term)
}
}
private fun loadFromCache(term: String) {
viewModelScope.launch(Dispatchers.IO) {
val list = repository.getSearchResults(term)
userData.postValue(list)
}
}
private fun clearSearchResults(term: String) {
viewModelScope.launch(Dispatchers.IO) {
repository.deleteSearchResults(term)
}
}
}
应用程序模块
@Module
@InstallIn(SingletonComponent::class)
object APPModule {
@Singleton
@Provides
fun getAppDB(context: Application): AppDatabase {
return AppDatabase.getAppDB(context)
}
@Singleton
@Provides
fun getDao(appDB: AppDatabase): AppDao {
return appDB.getDAO()
}
@Provides
fun provideFirebaseFirestore() = FirebaseFirestore.getInstance()
@Provides
fun provideUsersRef(db: FirebaseFirestore) = db.collection("users")
}
3条答案
按热度按时间cygmwpex1#
我在这个项目中使用多模块。id
com.google.gms.google-services
到应用程序目录和解决。rqdpfwrv2#
1.在build.gradle(项目)的依赖项中添加以下内容:
1.在build.gradle(模块)中添加以下内容:
1.在最后一行代码中添加以下内容:
kupeojn63#
我遇到这个问题,因为谷歌服务SDK版本不工作与gradle版本。
也许你可以试试这个方向。
原始项目build.gradle配置是正确的。
最后通过查找兼容的SDK版本来解决。