Я пытаюсь загрузить фотографию, которую я сохранил на firebase, она успешно сохранена, но не может загрузить изображение снова, ошибка:
"Ошибка загрузки для нуля с размером [0x0] класс com .bumptech.glide.load.engine.GlideException: Получена нулевая модель "
Я использую простую строку в своем коде
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
currentUser?.let{user ->
Glide.with(this)
.load(user.photoUrl)
.into(image_view)
Мои реализации в Build.Gradle
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.firebase:firebase-auth:19.3.0'
implementation 'com.google.firebase:firebase-database:19.2.1'
implementation 'com.google.firebase:firebase-firestore:21.4.1'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.navigation:navigation-fragment:2.2.1'
implementation 'androidx.navigation:navigation-ui:2.2.1'
implementation 'com.google.firebase:firebase-storage:19.1.1'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.navigation:navigation-fragment-ktx:2.2.1'
implementation 'androidx.navigation:navigation-ui-ktx:2.2.1'
implementation 'com.github.bumptech.glide:glide:4.8.0'
kapt 'com.github.bumptech.glide:compiler:4.8.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
Применен плагин для Gradle.Build
apply plugin: 'kotlin-kapt'
Спасибо за будущие ответы!
Кстати, вот весь мой код для фрагмента
класс NotificationsFragment: Fragment ( ) {
private lateinit var notificationsViewModel: NotificationsViewModel
private lateinit var imageUri: Uri
private val REQUEST_IMAGE_CAPTURE = 100
private val currentUser = FirebaseAuth.getInstance().currentUser
private val user = FirebaseDatabase.getInstance()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?):
View? {
notificationsViewModel =
ViewModelProviders.of(this).get(NotificationsViewModel::class.java)
return inflater.inflate(R.layout.fragment_notifications,container,false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
currentUser?.let{user ->
Glide.with(this)
.load(user.photoUrl)
.placeholder(R.drawable.ic_profilepicture_box_orange_24dp)
.into(image_view)
}
image_view.setOnClickListener {
takePictureIntent()
}
button_save.setOnClickListener{
}
}
private fun takePictureIntent() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { pictureIntent ->
pictureIntent.resolveActivity(activity?.packageManager!!)?.also {
startActivityForResult(pictureIntent, REQUEST_IMAGE_CAPTURE)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == AppCompatActivity.RESULT_OK) {
val imageBitmap = data?.extras?.get("data") as Bitmap
uploadImageAndSaveUri(imageBitmap)
}
}
private fun uploadImageAndSaveUri(bitmap: Bitmap) {
val baos = ByteArrayOutputStream()
val baos1 = ByteArrayOutputStream()
val storageRef = FirebaseStorage.getInstance()
.reference
.child("pics/${FirebaseAuth.getInstance().currentUser!!.uid}")
.child("uid" + ".JPEG")
.child("uid" + ".PNG")
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos1)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val image = baos.toByteArray()
val image1 = baos1.toByteArray()
val upload = storageRef.putBytes(image)
val upload1 = storageRef.putBytes(image1)
upload.addOnCompleteListener { uploadTask ->
if (uploadTask.isSuccessful){
storageRef.downloadUrl.addOnCompleteListener{urlTask ->
urlTask.result?.let{
imageUri = it
Toast.LENGTH_SHORT
}
}
}
}
upload1.addOnCompleteListener { uploadTask1 ->
if (uploadTask1.isSuccessful){
storageRef.downloadUrl.addOnCompleteListener{urlTask ->
urlTask.result?.let{
imageUri = it
}
}
}
}
progressbar_pic.visibility = View.VISIBLE
upload.addOnCompleteListener { uploadTask ->
progressbar_pic.visibility = View.INVISIBLE
if (uploadTask.isSuccessful) {
storageRef.downloadUrl.addOnCompleteListener { urlTask ->
urlTask.result?.let {
imageUri = it
imageUri.toString()
image_view.setImageBitmap(bitmap)
}
}
} else {
uploadTask.exception?.let {
Toast.makeText(activity, "Upload Failed", Toast.LENGTH_SHORT).show();
}
}
}
}
}
Я исправил это, мне пришлось добавить еще несколько кодов и отредактировать некоторые, это было исправлением, чтобы сохранить URL-адрес и фотографию.
private fun uploadImagetoFirebaseStorage(){
if (selectedPhotoUri == null) return
val filename = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$filename")
ref.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
Log.d("dsa","$it")
ref.downloadUrl.addOnSuccessListener {
it.toString()
saveUsertoFirebaseDatabase(it.toString())
}
}
}
private fun saveUsertoFirebaseDatabase(profileImageUrl: String){
val uid = FirebaseAuth.getInstance().uid ?: ""
val ref = FirebaseDatabase.getInstance().getReference("/users/$uid")
val user = User(uid,username_edittext_register.text.toString(),profileImageUrl)
ref.setValue(user)
.addOnSuccessListener {
Log.d("","Saved!!!!!!")
}
}
}
класс User (допустимое: String, val username: String, val profileImageUrl: String)
тогда я просто использовал модуль Glide, как вы обычно его используете
currentUser?.let{user ->
Glide.with(this)
.load(user.photoUrl)
.into(image_view)
}