Im trying to pass an image from my Activity ViewModel to Fragment, the Fragment Receive the data but it doesnt showed up on the fragment. Here is my code
Main Activity ViewModel
val storageRef = FirebaseStorage.getInstance().reference.child("Users/$nisSiswa.png")
val file = File.createTempFile("image", "png")
storageRef.getFile(file).addOnSuccessListener {
val bitmap : Bitmap = BitmapFactory.decodeFile(file.absolutePath)
val bitmapString = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bitmapString)
val byteArray : ByteArray = bitmapString.toByteArray()
profileBundle.putByteArray("foto", byteArray)
profilFragment.arguments = profileBundle
crashlytics.log("Bundle Dikirimkan ke Fragment")
loadingDialog.dismissLoading()
}
And here is my fragment Code to retrieve the image
super.onViewCreated(view, savedInstanceState)
binding.tvNamaSiswa.setText(arguments?.getString("nama"))
binding.tvNisSiswa.setText(arguments?.getString("nis"))
binding.tvEmailSiswa.setText(arguments?.getString("email"))
val byteFoto = arguments?.getByteArray("foto")
if (byteFoto != null) {
crashlytics.log("Data Berhasil Diterima Profile Fragment")
val bitmapFoto : Bitmap = BitmapFactory.decodeByteArray(byteFoto,0, DEFAULT_BUFFER_SIZE)
val encoded : ByteArray? = Base64.decode(byteFoto, Base64.DEFAULT)
val bitmap = encoded?.let { BitmapFactory.decodeByteArray(encoded, 0, it.size) }
binding.ivProfil.setImageBitmap(bitmapFoto)
} else {
Toast.makeText(this.context, "File Bitmap Kosong", Toast.LENGTH_SHORT).show()
binding.ivProfil.setImageResource(R.drawable.user_foto)
}
CodePudding user response:
You shouldn't really be passing bitmaps around in Bundle
s, they're not meant for large amounts of data. It would be better to pass that string reference you're using to fetch it ("Users/$nisSiswa.png"
) and let the Fragment
handle fetching and displaying it.
Or use a ViewModel
that the activity can pass a reference to, so the data fetch happens, and the fragment observe
s it and displays the current data.
You should also probably be using a library like Glide to display your images, which is the official recommendation - just makes things easier for you!