Adding user profile picture in Kotlin - android

I've recently started programming in Kotlin and cannot seem to add a profile picture to a user when registering it.
According to the code here, I can access to the gallery and retrieve the image information. The picture will appear on screen, but after registering the user the image url will not appear anywhere.
class RegisterUser : AppCompatActivity() {
private val database = FirebaseDatabase.getInstance()
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
private val UserCreation = database.getReference("Usuarios")
private val pickImage = 100
private var imageUri: Uri? = null
lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register_user)
Goback.setOnClickListener {
val Gobackou = Intent(this, MainActivity::class.java)
startActivity(Gobackou)
}
RegisterConfirm.setOnClickListener {
val SetUser = SetUser.text.toString()
val SetPass = setPass.text.toString()
val SetEmail = SetEmail.text.toString()
if (SetUser.isEmpty() && SetPass.isEmpty() && SetEmail.isEmpty()) {
Toast.makeText(this, "Faltan Campos", Toast.LENGTH_SHORT).show()
} else {
RegisterUserv2(SetEmail, SetPass, SetUser)
}
}
selectPP.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, pickImage)
}
}
var selectedPhotoUri: Uri? = null
//guardar la foto de perfil
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == pickImage) {
val selectedPhotoUri = data?.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
val bitmapDrawable = BitmapDrawable(bitmap)
userimg.setBackgroundDrawable(bitmapDrawable)
}
}
private fun RegisterUserv2(email: String, password: String, user: String) {
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
uploadimage()
UltrasaveUsuario(Usuarios(auth.currentUser!!.uid, user, password, email))
val Gobackou = Intent(this, MainActivity::class.java)
startActivity(Gobackou)
} else {
Toast.makeText(this, "Registro ERROR", Toast.LENGTH_LONG).show()
}
}
}
private fun UltrasaveUsuario(usuario: Usuarios) {
val mensajeFirebase = UserCreation.push()
usuario.id = mensajeFirebase.key ?: ""
mensajeFirebase.setValue(usuario)
}
private fun uploadimage(imageurl: String){
if (selectedPhotoUri == null) return
val filename = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$filename/")
ref.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
ref.downloadUrl.addOnSuccessListener{
}
}
}
}

Since you are using firebase I will show you how to save firebase storage.
private fun uploadImage() {
if (mSelectedImageFileUri != null) {
val sRef: StorageReference = FirebaseStorage.getInstance().reference.child(
"users/ $uid/profile.jpg"
)
sRef.putFile(mSelectedImageFileUri!!)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.metadata!!.reference!!.downloadUrl
.addOnSuccessListener { url ->
}
}.addOnFailureListener {
//error
}
} else {
}
}
then you will take this picture using the user id to take .
firebase>storage to view the image
getImage
val sRef: StorageReference = FirebaseStorage.getInstance().reference.child(
"users/ $uid/profile.jpg"
)
sRef.downloadUrl.addOnSuccessListener {
Picasso.get().load(it).into(globalprofileImage)
}
Build.gradle
implementation 'com.squareup.picasso:picasso:2.71828'
https://www.youtube.com/watch?v=nNYLQcmB7AU&t=449s&ab_channel=SmallAcademy

Related

updating storage with the use of io fotoapparat library | Kotlin

I make a mobile application using the "io fotoapparat" library and I want to create a document with a random id and in the document in the id field, add the document id, the photo we will take was updated in the firebase store and in the previously made about the same id in the receipt collection when taking a photo
link from which I took "io fotoapparat"
EDIT
add to firestore document
binding.button.setOnClickListener {
// Inflate the layout for this fragment
val biedronka = "biedronka"
val price = "20"
val img = " "
val identificator = " "
val from = biedronka
val value = price
val image = img
val idd = identificator
val db = Firebase.firestore
val data = hashMapOf(
"from" to from,
"value" to value,
"image" to image,
"id" to idd
)
db.collection("receipts")
.add(data)
.addOnSuccessListener { documentReference ->
Log.d(SCAN_DEBUG, "DocumentSnapshot written with ID: ${documentReference.id}")
db.collection("receipts")
.document(documentReference.id)
.update("id", documentReference.id)
.addOnSuccessListener {
}
}
.addOnFailureListener { e ->
Log.w(SCAN_DEBUG, "Error adding document", e)
}
}
2 add to storage and to document (doesnt work)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CAPTURE_IMAGE && resultCode == RESULT_OK) {
val uid = profileVm.user.value?.uid!!
val imageBitmap = data?.extras?.get("data") as Bitmap
val userImage = binding.userImg
val stream = ByteArrayOutputStream()
val result = imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
val byteArray = stream.toByteArray()
if (result) profileVm.uploadUserPhoto(byteArray, "$uid.jpg")
}
}
repository to 2
fun uploadReceiptPhoto(bytes: ByteArray) {
storage.getReference("receipts")
.child("${docId}.jpg")
.putBytes(bytes)
.addOnCompleteListener{
Log.d(REPO_DEBUG, "COMPLETE UPLOAD PHOTO")
}
.addOnSuccessListener {
getReceiptPhotoDownloadUrl(it.storage)
}
.addOnFailureListener {
Log.d(REPO_DEBUG, it.message.toString())
}
}
private fun getReceiptPhotoDownloadUrl(storage: StorageReference) {
storage.downloadUrl
.addOnSuccessListener {
updateReceiptPhoto(it.toString())
}
.addOnFailureListener {
Log.d(REPO_DEBUG, it.message.toString())
}
}
private fun updateReceiptPhoto(url: String) {
cloud.collection("receipts")
.document(docId)
.update("image", url)
.addOnSuccessListener {
Log.d(REPO_DEBUG, "UPDATE USER PHOTO")
}
.addOnFailureListener {
Log.d(REPO_DEBUG, it.message.toString())
}
}
THE REST OF THE CODE (camera code "io fotoapparat" and take pictures)
class ScanFragment : Fragment(), OnReceiptsItemAdd {
private var _binding: FragmentScanBinding? = null
private val binding get() = _binding!!
private val scanVm by viewModels<ScanViewModel>()
private val SCAN_DEBUG = "SCAN_DEBUG"
private var fotoapparat: Fotoapparat? = null
private var fotoapparatState: FotoapparatState? = null
private var cameraStatus: CameraState? = null
private var flashState: FlashState? = null
private val permissions = arrayOf(Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentScanBinding.inflate(inflater, container, false)
createFotoapparat()
cameraStatus = CameraState.BACK
flashState = FlashState.OFF
fotoapparatState = FotoapparatState.OFF
binding.fabSwitchCamera.setOnClickListener {
switchCamera()
}
binding.fabFlash.setOnClickListener {
changeFlashState()
}
return binding.root
}
private fun createFotoapparat(){
val cameraView = binding.cameraView
fotoapparat = Fotoapparat(
context = requireContext(),
view = cameraView,
scaleType = ScaleType.CenterCrop,
lensPosition = back(),
logger = loggers(
logcat()
),
cameraErrorCallback = { error ->
println("Recorder errors: $error")
}
)
}
private fun changeFlashState() {
fotoapparat?.updateConfiguration(
CameraConfiguration(
flashMode = if(flashState == FlashState.TORCH) off() else torch()
)
)
flashState = if(flashState == FlashState.TORCH) FlashState.OFF
else FlashState.TORCH
}
private fun switchCamera() {
fotoapparat?.switchTo(
lensPosition = if (cameraStatus == CameraState.BACK) front() else back(),
cameraConfiguration = CameraConfiguration()
)
cameraStatus = if(cameraStatus == CameraState.BACK) CameraState.FRONT
else CameraState.BACK
}
private fun takePhoto() {
if (hasNoPermissions()) {
requestPermission()
}else{
fotoapparat
?.takePicture()
?.toBitmap()
}
}
override fun onStart() {
super.onStart()
if (hasNoPermissions()) {
requestPermission()
}else{
fotoapparat?.start()
fotoapparatState = FotoapparatState.ON
}
}
private fun hasNoPermissions(): Boolean{
return ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
}
private fun requestPermission(){
ActivityCompat.requestPermissions(requireActivity(), permissions,0)
}
override fun onStop() {
super.onStop()
fotoapparat?.stop()
FotoapparatState.OFF
}
}
enum class CameraState{
FRONT, BACK
}
enum class FlashState{
TORCH, OFF
}
enum class FotoapparatState{
ON, OFF
}

Firebase recyclerview images disappear after reload application

When I just added it, everything is fine, but when I restart the application, only textViews is displayed. There is an empty space instead of an imageView.
My recycler adapter:
class PersonAdapter(options: FirebaseRecyclerOptions<Outfit?>) :
FirebaseRecyclerAdapter<Outfit, personsViewHolder>(options) {
override fun onBindViewHolder(holder: personsViewHolder, position: Int, model: Outfit) {
holder.name.text = model.name
holder.brand.text = model.brand
holder.size.text = model.size
holder.comment.text = model.comment
holder.price.text = model.price
Picasso.get().load(model.imageUrl).into(holder.imageView) //Glide analog
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): personsViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.recycler_item, parent, false)
return personsViewHolder(view)
}
class personsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var name: TextView = itemView.findViewById(R.id.tv_name_value)
var brand: TextView = itemView.findViewById(R.id.tv_brand_value)
var size: TextView = itemView.findViewById(R.id.tv_size_value)
var comment: TextView = itemView.findViewById(R.id.tv_comment_value)
var price: TextView = itemView.findViewById(R.id.tv_price_value)
var imageView: ImageView = itemView.findViewById(R.id.imageView)
}
}
Class what add to database:
private var dataBase: DatabaseReference? = null
private lateinit var outfitImage: ImageView
private var imageUri: Uri? = null
private var id: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_outfit)
nameView = findViewById(R.id.et_outfitName)
brandView = findViewById(R.id.et_outfitBrand)
sizeView = findViewById(R.id.et_outfitSize)
commentView = findViewById(R.id.et_outfitComment)
priceView = findViewById(R.id.et_outfitPrice)
btnAdd = findViewById(R.id.btn_addOutfit)
btnLoad = findViewById(R.id.btn_load)
btnAdd?.setOnClickListener {
onClickSave()
Toast.makeText(this, "Added to database", Toast.LENGTH_SHORT).show()
startActivity(Intent(this, MainActivity::class.java))
}
btnLoad?.setOnClickListener {
onClickRead()
}
outfitImage = findViewById(R.id.iv_upload_image)
outfitImage.setOnClickListener {
chooseImage()
}
}
//SAVE BUTTON
private fun onClickSave() {
dataBase = FirebaseDatabase.getInstance().getReference(UUID.randomUUID().toString())
dataBase?.setValue(
Outfit(
nameView?.text.toString(),
brandView?.text.toString(),
sizeView?.text.toString(),
commentView?.text.toString(),
priceView?.text.toString(),
imageUri.toString()
)
)
uploadImageToFirebase(imageUri!!)
}
//----------------UPLOAD IMAGE-----------------------
private fun chooseImage() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(
Intent.createChooser(intent, "Please select..."), 1
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null && data.data != null) {
// Get the Uri of data
imageUri = data.data
outfitImage.setImageURI(imageUri)
}
}
private fun uploadImageToFirebase(imageUri: Uri) {
val pd: ProgressDialog = ProgressDialog(this)
pd.setTitle("Uploading image...")
pd.show()
val fileName = UUID.randomUUID().toString()
val refStorage = FirebaseStorage.getInstance().reference.child("images/$fileName")
refStorage.putFile(imageUri)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.storage.downloadUrl.addOnSuccessListener {
pd.dismiss()
Snackbar.make(
findViewById(android.R.id.content),
"Image uploaded.",
Snackbar.LENGTH_LONG
)
val imageUrl = it.toString()
}
}
.addOnFailureListener { e ->
print(e.message)
pd.dismiss()
}
//progressbar
.addOnProgressListener {
var progressPercents: Double = (100.00 * it.bytesTransferred / it.totalByteCount)
pd.setMessage("Percentage: $progressPercents%")
}
}
}
Logic at MainActivity:
mbase = FirebaseDatabase.getInstance().reference
recyclerView = findViewById(R.id.recycler1)
recyclerView.layoutManager = LinearLayoutManager(this)
val options = FirebaseRecyclerOptions.Builder<Outfit>()
.setQuery(mbase!!, Outfit::class.java)
.build()
// Connecting object of required Adapter class to the Adapter class itself
adapter = PersonAdapter(options)
// Connecting Adapter class with the Recycler view*/
recyclerView.adapter = adapter
swipeRefreshLayout.setOnRefreshListener(this)
Here are screenshots of how everything looks in the backend:
my backend
images storage
private fun uploadToFirebase() {
val pd: ProgressDialog = ProgressDialog(this)
pd.setTitle("Uploading image...")
pd.show()
val fileName = UUID.randomUUID().toString()
val refStorage = FirebaseStorage.getInstance().getReference("/images/$fileName")
refStorage.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
pd.dismiss() //close loading
refStorage.downloadUrl.addOnSuccessListener {
saveDataToDatabase(it.toString()) //get downloading url
}
}
.addOnFailureListener { e ->
print(e.message)
pd.dismiss()
}
//progressbar
.addOnProgressListener {
var progressPercents: Double = (100.00 * it.bytesTransferred / it.totalByteCount)
pd.setMessage("Percentage: $progressPercents%")
}
}
private fun saveDataToDatabase(imageUrl:String) {
dataBase = FirebaseDatabase.getInstance().getReference(UUID.randomUUID().toString())
dataBase?.setValue(
Outfit(
nameView?.text.toString(),
brandView?.text.toString(),
sizeView?.text.toString(),
commentView?.text.toString(),
priceView?.text.toString(),
imageUrl
)
)
}
Here is my solution. Bad url was a ploblem.

Problem in retrieving chat message from firebase

I am trying to build a chatting application but whenever I click on the any of the users it crashes.
class MessegeActivity : AppCompatActivity() {
var userIdVisit: String = ""
var currentUserId : FirebaseUser?=null
var chatsAdpater:ChatAdpater?=null
var mChatList:List<Chat>?=null
lateinit var recycler_view_chat:RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_messege)
intent = intent
userIdVisit = intent.getStringExtra("visit_id")
currentUserId =FirebaseAuth.getInstance().currentUser!!
recycler_view_chat =findViewById(R.id.recycler_view_chat)
recycler_view_chat.setHasFixedSize(true)
var linearLayoutManager =LinearLayoutManager(applicationContext)
linearLayoutManager.stackFromEnd =true
recycler_view_chat.layoutManager =linearLayoutManager
//showing other username and profile dp
val reference = FirebaseDatabase.getInstance().reference
.child("Users").child(userIdVisit)
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
val user: Users? = p0.getValue(Users::class.java)
username_mchat.text = user!!.getFullName()
Picasso.get().load(user.getImg()).into(profile_image_mchat)
retreiveMsg(currentUserId!!.uid,userIdVisit,user.getImg())
}
override fun onCancelled(error: DatabaseError) {
}
})
send_messege_btn.setOnClickListener {
val messege = text_messege.text.toString()
if (messege == "") {
Toast.makeText(this#MessegeActivity, "Please write something!!", Toast.LENGTH_SHORT)
.show()
} else {
sendMessegeToUser(currentUserId!!.uid, userIdVisit, messege)
}
text_messege.setText("")
}
attach_image_file.setOnClickListener {
val intent = Intent()
intent.action = Intent.ACTION_GET_CONTENT
intent.type = "image/*"
startActivityForResult(Intent.createChooser(intent, "Pick Image"), 198)
}
}
private fun sendMessegeToUser(senderId: String, receiverId: String?, messege: String) {
val reference = FirebaseDatabase.getInstance().reference
val messegeKey:String = reference.push().key!!
val messegeHashMap = HashMap<String, Any?>()
messegeHashMap["sender"] = senderId
messegeHashMap["messege"] = messege
messegeHashMap["receiver"] = receiverId
messegeHashMap["isseen"] = "false"
messegeHashMap["url"] = ""
messegeHashMap["messegeId"] = messegeKey
reference.child("Chats").child(messegeKey).setValue(messegeHashMap)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val ChatsListRefernce =
FirebaseDatabase.getInstance().reference.child("ChatLists").child(currentUserId!!.uid).child(userIdVisit)
ChatsListRefernce.addListenerForSingleValueEvent(object :ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
if(!p0.exists())
{
ChatsListRefernce.child("id").setValue(userIdVisit)
}
val ChatsListReceiverRefernce =
FirebaseDatabase.getInstance().reference.child("ChatLists").child(userIdVisit).child(currentUserId!!.uid)
ChatsListReceiverRefernce.child("id").setValue(currentUserId!!.uid)
}
override fun onCancelled(error: DatabaseError) {
}
})
//notification
// val reference = FirebaseDatabase.getInstance().reference
// .child("Users").child(currentUserId!!.uid)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 198 && resultCode ==RESULT_OK && data!=null && data.data != null) {
val progressBar = ProgressDialog(this)
progressBar.setMessage("Please wait")
progressBar.show()
val fileUri = data.data
val storageRef = FirebaseStorage.getInstance().reference.child("Chat Images")
val ref = FirebaseDatabase.getInstance().reference
val messegeId = ref.push().key
val filepath = storageRef.child("$messegeId.jpg")
var uploadTask: StorageTask<*>
uploadTask = filepath.putFile(fileUri!!)
uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
return#Continuation filepath.downloadUrl
}).addOnCompleteListener { task ->
val downloadUrl = task.result
val url = downloadUrl.toString()
val messegeHashMap = HashMap<String,Any?>()
messegeHashMap["sender"] = currentUserId!!.uid
messegeHashMap["messege"] = "sent you an image"
messegeHashMap["receiver"] = userIdVisit
messegeHashMap["isseen"] = "false"
messegeHashMap["url"] = url
messegeHashMap["messegeId"] = messegeId.toString()
ref.child("Chats").child(messegeId!!).setValue(messegeHashMap)
progressBar.dismiss()
}
}
}
private fun retreiveMsg(senderId: String, receiverId: String?, recieverimgUrl: String?) {
mChatList =ArrayList()
val reference =FirebaseDatabase.getInstance().reference.child("Chats")
reference.addValueEventListener(object:ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
(mChatList as ArrayList<Chat>).clear()
for (snapshot in p0.children)
{
val chat= snapshot.getValue(Chat::class.java)
if(chat!!.getReceiver().equals(senderId)&& chat.getSender().equals(receiverId) ||
chat.getReceiver().equals(receiverId)&& chat.getSender().equals(senderId))
{
(mChatList as ArrayList<Chat>).add(chat)
}
chatsAdpater = ChatAdpater(this#MessegeActivity,(mChatList as ArrayList<Chat>),recieverimgUrl!!)
recycler_view_chat.adapter =chatsAdpater
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
package com.insidecoderz.trails2.Model
class Chat {
private var sender:String =""
private var messege:String =""
private var receiver:String =""
private var isseen :Boolean= false
private var url:String =""
private var messegeId:String =""
constructor()
constructor(
sender: String,
messege: String,
receiver: String,
isseen:Boolean,
url: String,
messegeId: String
) {
this.sender = sender
this.messege = messege
this.receiver = receiver
this.isseen = isseen
this.url = url
this.messegeId = messegeId
}
fun getSender(): String?{
return sender
}
fun setSender(sender: String){
this.sender =sender
}
fun getMessege(): String?{
return messege
}
fun setMessege(messege: String){
this.messege =messege
}
fun getReceiver(): String?{
return receiver
}
fun setReceiver(receiver: String){
this.receiver =receiver
}
fun isIsSeen(): Boolean {
return isseen
}
fun setIsSeen(isseen: Boolean){
this.isseen =isseen
}
fun getUrl(): String?{
return url
}
fun setUrl(url: String){
this.url =url
}
fun getMessegeId(): String?{
return messegeId
}
fun setMessegeId(messegeId: String){
this.messegeId =messegeId
}
}
I am facing this issue again and again, whenever I run the application in the application in the emulator it crashes with showing this error.
2020-08-22 23:19:59.920 17005-17005/com.insidecoderz.trails2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.insidecoderz.trails2, PID: 17005
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Boolean to type com.insidecoderz.trails2.Model.Chat
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:435)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:231)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:79)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.insidecoderz.trails2.MessegeActivity$retreiveMsg$1.onDataChange(MessegeActivity.kt:202)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7134)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:536)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
If you access the id of the user with the following code val reference = FirebaseDatabase.getInstance().reference.child("Users").child(userIdVisit) and then you try to get the data as a model Chat you can not do that, instead try FirebaseDatabase.getInstance().reference.child("Users").This way you'll be able to get your data as model Chat but it won't be the id you want, also if at the node "Users" you have more users then you'll obtain all the users info using the model Chat
If you need the information for the userIdVisit then you can you do the following
snapshot.child("userInfo1").getValue();
snapshot.child("userInfo2").getValue();
This is the sample for java, you should adapt it for kotlin, I'm sorry for not providing the sample in kotlin but I'm not familiar with it

Kotlin - Firebase - Save Uri to user's folder images keeps saving wrong Uri

I'm trying to build an Instagram-like app, an issue occurs when I try to save taken photo to user's folder "images" on Firebase database. It keeps saving something like "com.google.firebase.storage.UploadTask#62873ce"
Instead of link like this:
"https://firebasestorage.googleapis.com/v0/b/gramgram-1b3f9.appspot.com/o/users%2F7q3pqR6GnHMx7NSdgoBqZETkrS32%2Fphoto?alt=media&token=bbcbe556-1de5-4176-aba2-599f829e65"
here is my Share Activity.kt
class ShareActivity : BaseActivity(2) {
private val TAG = "ShareActivity"
private lateinit var mCamera: CameraHelper
private lateinit var mFirebase: FirebaseHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_share)
Log.d(TAG, "onCreate")
mFirebase =FirebaseHelper(this)
mCamera = CameraHelper(this)
mCamera.takeCameraPicture()
back_image.setOnClickListener{finish()}
share_text.setOnClickListener{share()}
}
#SuppressLint("MissingSuperCall")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == mCamera.REQUEST_CODE){
if (resultCode == RESULT_OK){
GlideApp.with(this).load(mCamera.imageUri).centerCrop().into(post_image)
} else{
finish()
}
}
}
private fun share(){
val imageUri = mCamera.imageUri
if (imageUri != null){
val uid = mFirebase.auth.currentUser!!.uid
mFirebase.storage.child("users").child(uid).child("images")
.child(imageUri.lastPathSegment!!).putFile(imageUri).addOnCompleteListener {
if (it.isSuccessful){
mFirebase.database.child("images").child(uid).push()
.setValue(it.toString())
.addOnCompleteListener{
if (it.isSuccessful){
startActivity(Intent(this,
ProfileActivity::class.java))
finish()
} else {
showToast(it.exception!!.message!!)
}
}
} else {
showToast(it.exception!!.message!!)
}
}
}
}
}
here are my uploadUserPhoto and updateUsePhoto functions in FirebaseHelper.kt
fun uploadUserPhoto(photo: Uri, onSuccess: (String) -> Unit) {
val uTask = storage.child("users/${auth.currentUser!!.uid}/photo").putFile(photo)
storage.child("users/${auth.currentUser!!.uid}/photo").putFile(photo)
.addOnCompleteListener {
if (it.isSuccessful) {
uTask.continueWithTask { _ ->
storage.child("users/${auth.currentUser!!.uid}/photo").downloadUrl
}.addOnCompleteListener{
if (it.isSuccessful && it.result != null) {
onSuccess(it.result.toString())
} else {
activity.showToast(it.exception!!.message!!)
}
}
}
}
}
fun updateUserPhoto( photoUrl: String, onSuccess: () -> Unit){
database.child("users/${auth.currentUser!!.uid}/photo").setValue(photoUrl)
.addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
activity.showToast(it.exception!!.message!!)
}
}
}
I am not sure how to set my private fun share() to upload correct URL to User's "images" folder
and here is my CameraHelper.kt
class CameraHelper(private val activity: Activity){
var imageUri: Uri? = null
val REQUEST_CODE = 1
private val simpleDateFormat = SimpleDateFormat(
"yyyyMMdd_HHmmss",
Locale.US
)
fun takeCameraPicture() {
val intent =
Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (intent.resolveActivity(activity.packageManager) != null) {
val imageFile = createImageFile()
imageUri = FileProvider.getUriForFile(
activity,
"com.example.homeactivity.fileprovider",
imageFile
)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
activity.startActivityForResult(intent, REQUEST_CODE)
}
}
private fun createImageFile(): File {
val storageDir: File? = activity.getExternalFilesDir(
Environment.DIRECTORY_PICTURES
)
return File.createTempFile(
"JPEG_${simpleDateFormat.format(Date())}_",
".jpg",
storageDir
)
}
}
You're not using the result from putFile(imageUri) correctly. You have:
putFile(imageUri).addOnCompleteListener {
if (it.isSuccessful){
mFirebase.database.child("images").child(uid).push()
.setValue(it.toString())
That it.toString() is not the URL. it is the UploadTask object returned by putFile(). You can't just turn that into a string - it's a Task that you need to observe to get the result.
You seem to be fetching a download URL correctly in uploadUserPhoto using downloadUrl to fetch the URL to write. You're going to have to do it that way instead.
See also the documentation and this question.
I managed to solve it.
In case anyone needs it, here is working function share():
private fun share(){
val imageUri = mCamera.imageUri
if (imageUri != null){
val uid = mFirebase.auth.currentUser!!.uid
val uTask = mFirebase.storage.child("users").child(uid).child("images").child(imageUri.lastPathSegment!!).putFile(imageUri)
mFirebase.storage.child("users").child(uid).child("images").child(imageUri.lastPathSegment!!).putFile(imageUri)
.addOnCompleteListener {
if (it.isSuccessful) {
uTask.continueWithTask { _ ->
mFirebase.storage.child("users").child(uid).child("images")
.child(imageUri.lastPathSegment!!).downloadUrl
}.addOnCompleteListener {
if (it.isSuccessful && it.result != null)
mFirebase.database.child("images").child(uid).push()
.setValue(it.result.toString())
.addOnCompleteListener {
if (it.isSuccessful) {
startActivity(
Intent(
this,
ProfileActivity::class.java
)
)
finish()
} else {
showToast(it.exception!!.message!!)
}
}
}
} else {
showToast(it.exception!!.message!!)
}
}
}
}

Getting a class not found exception along with cannot decode stream exception while trying to retrieve images

I am getting a class not found exception when trying to click an image from the camera or while fetching it from the directory. The code is in kotlin and has been given below.
This is the class which implements the functionality to capture an image or picks them from the gallery.
The methods _openCamera() and openFileSelector() are implemented.
The main motive was to capture the images and upload them in the server but the implemented methods doesn't give the proper results.
class MainActivity : AppCompatActivity() {
private var drawerResult: Drawer? = null
private var jobschedular: JobScheduler? = null
private var jobschedularCode: Int = 1
private var phoneNumber: String? = null
private var toolbar: Toolbar? = null
private var familyId: String? = null
val TAG: String? = "Activity_Name"
val REQUEST_IMAGE_CAPTURE = 1
val REQUEST_CODE_FOR_GALLERY_CAPTURE = 2
var photoFile: File? = null
var progressDialog: Dialog? = null
private var doubleBackToExitPressedOnce = false
#SuppressLint("PrivateResource")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
Log.d(TAG, "Inside MainActivity")
//onclick listener for open camera
onclickListenerForOpenCamera()
//starting the services here . .
val service_checkAddedtoFamily = Intent(this, checkAddedToFamily::class.java)
startService(service_checkAddedtoFamily)
val service_checkDocsToBeVerified = Intent(this, checkDocsToBeVerified::class.java)
startService(service_checkDocsToBeVerified)
/*findViewById<Button>(R.id.scan).setOnClickListener {
val i = Intent(this, Testers::class.java)
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
startActivity(i)
overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
}*/
//onclick listener for select image button
attach_onclick_listener_to_add_photos_from_gallery()
//onclick listener for select pdf files
onclickListenerForSelectPdfFile()
//get toolbar for drawer
toolbar = findViewById(R.id.toolbar_tabs)
//get phone number
val loginInfo = applicationContext.getSharedPreferences("loginInfo", Context.MODE_PRIVATE)
phoneNumber = loginInfo.getString("phoneNumber", "")
//onclick listener for upload button
//onclickListenerForUploadButton()
//onclick listener for retrieve button
onclickListenerForRetrieveButton()
//on click permanent diseases button
//onclickPermanentDiseasesButtton()
//navigation drawer
left_drawer(this, this#MainActivity, toolbar!!).createNavigationDrawer()
//verify auto upload
verifyAutoLoginInformation()
//create Sqlite database
DB_HELPER(this#MainActivity).writableDatabase
//get job schedular service
jobschedular = applicationContext.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
schedulTheJobForHealthGoals()
schedulTheJobForHealthInsurance()
setPreferencesForNutrition()
schedulTheJobForNutrition()
schedulTheJobForSyncNutritionOnline()
}
/*override fun onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed()
return
}
this.doubleBackToExitPressedOnce = true
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show()
Handler().postDelayed(Runnable { doubleBackToExitPressedOnce = false }, 2000)
}*/
//job schedular
fun schedulTheJobForHealthGoals() {
val builder = JobInfo.Builder(jobschedularCode, ComponentName(this#MainActivity, health_goals_services::class.java))
.setPersisted(true)
.setPeriodic(5000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setRequiresCharging(false)
.setRequiresDeviceIdle(false)
val bundle = PersistableBundle()
bundle.putString("key", "value")
builder.setExtras(bundle)
val s_response = jobschedular!!.schedule(builder.build())
if (s_response <= 0) {
//something goes wrong
}
}
fun schedulTheJobForHealthInsurance() {
val builder = JobInfo.Builder(jobschedularCode, ComponentName(this#MainActivity, health_insurance_service::class.java))
.setPersisted(true)
.setPeriodic(5000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setRequiresCharging(false)
.setRequiresDeviceIdle(false)
val bundle = PersistableBundle()
bundle.putString("key", "value")
builder.setExtras(bundle)
val s_response = jobschedular!!.schedule(builder.build())
if (s_response <= 0) {
//something goes wrong
}
}
fun schedulTheJobForNutrition() {
val builder = JobInfo.Builder(jobschedularCode, ComponentName(this#MainActivity, nutrition_service::class.java))
.setPersisted(true)
.setPeriodic(5000) //change to 1 hour
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setRequiresCharging(false)
.setRequiresDeviceIdle(false)
val bundle = PersistableBundle()
bundle.putString("key", "value")
builder.setExtras(bundle)
val s_response = jobschedular!!.schedule(builder.build())
if (s_response <= 0) {
//something goes wrong
}
}
fun setPreferencesForNutrition() {
val nutritionInfo = getSharedPreferences("nutrition", Context.MODE_PRIVATE)
val editor = nutritionInfo.edit()
editor.putString("breakFastTime_Hour", "7")
editor.putString("lunchTime_Hour", "14") //TODO: change to 13
editor.putString("DinnerTime_Hour", "20")
editor.apply()
}
fun schedulTheJobForSyncNutritionOnline() {
val builder = JobInfo.Builder(jobschedularCode, ComponentName(this#MainActivity, sync_nutrition_online::class.java))
.setPersisted(true)
.setPeriodic(5000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setRequiresCharging(false)
.setRequiresDeviceIdle(false)
val bundle = PersistableBundle()
bundle.putString("key", "value")
builder.setExtras(bundle)
val s_response = jobschedular!!.schedule(builder.build())
if (s_response <= 0) {
//something goes wrong
}
}
//buttons on home screen
/*fun onclickListenerForUploadButton(){
findViewById<ImageView>(R.id.uploadButton).setOnClickListener{
openModeOfUploadActivity()
}
}*/
fun onclickListenerForRetrieveButton() {
findViewById<Button>(R.id.retrieveButton).setOnClickListener {
openHistoryActivity()
}
}
/*fun onclickPermanentDiseasesButtton(){
findViewById<Button>(R.id.permanentDiseasesButton).setOnClickListener{
openPermanentDiseases()
}
}*/
/*fun openModeOfUploadActivity(){
val intent = Intent(this,MainActivity::class.java)
startActivity(intent)
}*/
fun openHistoryActivity() {
val intent = Intent(this, history_pickFamilyMember::class.java)
startActivity(intent)
overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
}
/*fun openPermanentDiseases(){
val intent = Intent(this,permanentDiseaese::class.java)
startActivity(intent)
}
*/
//verify auto login information
fun verifyAutoLoginInformation() {
val loginInfo = applicationContext.getSharedPreferences("loginInfo", Context.MODE_PRIVATE)
if (loginInfo.contains("familyOrIndividual") == true) {
//for family
if (loginInfo.getString("familyOrIndividual", "").toString() == "f") {
if (loginInfo.contains("phoneNumber") == true && loginInfo.contains("password") == true) {
val phoneNumber = loginInfo.getString("phoneNumber", "")
val password = loginInfo.getString("password", "")
individual_family_login(this#MainActivity).makeFamilyLoginApiRequest(phoneNumber, password)
} else {
left_drawer(this, this#MainActivity, toolbar!!).makeUserLogOut()
}
}
//for individual
if (loginInfo.getString("familyOrIndividual", "").toString() == "i") {
if (loginInfo.contains("phoneNumber") == true && loginInfo.contains("password") == true) {
val phoneNumber = loginInfo.getString("phoneNumber", "")
val password = loginInfo.getString("password", "")
individual_family_login(this#MainActivity).makeLoginApiRequest(phoneNumber, password)
} else {
left_drawer(this, this#MainActivity, toolbar!!).makeUserLogOut()
}
}
//for security
if (loginInfo.getString("familyOrIndividual", "").toString() != "i" && loginInfo.getString("familyOrIndividual", "").toString() != "f") {
left_drawer(this, this#MainActivity, toolbar!!).makeUserLogOut()
}
} else {
left_drawer(this, this#MainActivity, toolbar!!).makeUserLogOut()
}
}
//camera scan
fun onclickListenerForOpenCamera() {
findViewById<ImageView>(R.id.openCamera).setOnClickListener {
get_permissions_camera()
}
}
fun _openCamera() {
Log.d("Errors__", "inside _openCamera()")
try {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
try {
photoFile = createImageFile()
} catch (ex: Exception) {
Log.d("Errors__", "inside: " + ex.toString())
}
if (photoFile != null) {
val builder: StrictMode.VmPolicy.Builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
val photoURI: Uri = Uri.fromFile(photoFile!!)
Log.d("Path__", "photoURI: $photoURI")
Log.d("Path__", "photoURI.path: " + photoURI.path)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
}
}
} catch (e: Exception) {
Log.d("Errors__", "_openCamera" + e.toString())
}
}
fun createImageFile(): File {
Log.d("Errors__", "inside createImageFile()")
val mCurrentPhotoPath: String
val imageFileName = "camera"
val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath()
Log.d("Path__", "Image: $image")
return image
}
//file selector
fun onclickListenerForSelectPdfFile() {
findViewById<ImageView>(R.id.selectPdfFile).setOnClickListener {
get_permissions_fileExplorer()
}
}
#SuppressLint("SdCardPath")
fun openFileSelector() {
val properties = DialogProperties()
properties.selection_mode = DialogConfigs.MULTI_MODE;
properties.selection_type = DialogConfigs.FILE_SELECT;
properties.root = File(DialogConfigs.DEFAULT_DIR);
properties.error_dir = File(DialogConfigs.DEFAULT_DIR);
properties.offset = File(DialogConfigs.DEFAULT_DIR);
properties.extensions = null;
val dialog: FilePickerDialog = FilePickerDialog(this#MainActivity, properties)
dialog.setTitle("Select a File")
dialog.setDialogSelectionListener(object : DialogSelectionListener {
override fun onSelectedFilePaths(files: Array<out String>?) {
convertPdfToImages(files!!)
}
})
dialog.show()
}
fun convertPdfToImages(files: Array<out String>) {
showProcessProgress()
doAsync {
var uriList: MutableList<Uri>? = mutableListOf()
val no_of_files = files.size
var counter = 0
while (counter < no_of_files) {
var pdfFile = File(files[counter])
val decodeService = DecodeServiceBase(PdfContext())
decodeService.setContentResolver(applicationContext.getContentResolver())
decodeService.open(Uri.fromFile(pdfFile))
val pageCount: Int = decodeService.getPageCount()
var i = 0
while (i < pageCount) {
val page: PdfPage = decodeService.getPage(i) as PdfPage
val rectF = RectF(0.toFloat(), 0.toFloat(), 1.toFloat(), 1.toFloat())
// do a fit center to 1920x1080
val scaleBy = 1
val with: Int = (page.getWidth() * scaleBy)
val height: Int = (page.getHeight() * scaleBy)
val bitmap: Bitmap = page.renderBitmap(with, height, rectF)
try {
val outputFile = File(applicationContext.externalCacheDir,
System.currentTimeMillis().toString() + ".jpg")
val outputStream = FileOutputStream(outputFile)
// a bit long running
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
uriList!!.add(Uri.fromFile(outputFile))
outputStream.close()
} catch (e: IOException) {
}
i++
}
counter++
}
uiThread {
progressDialog!!.hide()
openPreview(uriList!!)
Log.d("mess", "size: " + uriList.size + " " + uriList.toString())
}
}
}
//select image
fun attach_onclick_listener_to_add_photos_from_gallery() {
findViewById<ImageView>(R.id.selectImage).setOnClickListener {
get_permissions_gallery()
}
}
fun open_selector() {
Matisse.from(this)
.choose(MimeType.allOf())
.countable(true)
.maxSelectable(200)
.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
.thumbnailScale(0.85f)
.imageEngine(PicassoEngine())
.forResult(REQUEST_CODE_FOR_GALLERY_CAPTURE)
}
//activity results
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
var uriOfImage = Uri.fromFile(photoFile)
Log.d("fileCapturing__", "URI Image: $uriOfImage")
//start croper
CropImage.activity(uriOfImage)
.start(this)
}
if (requestCode == REQUEST_CODE_FOR_GALLERY_CAPTURE && resultCode == Activity.RESULT_OK) {
var selected_images = Matisse.obtainResult(data)
openPreview(selected_images!!)
}
//for croper
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
val result: CropImage.ActivityResult = CropImage.getActivityResult(data)
if (resultCode == RESULT_OK) {
doAsync {
val builder: StrictMode.VmPolicy.Builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
var resultUri: Uri = result.getUri()
//save cropped image for persisitance
val croppedImage = createImageFile() //empty
val outputStream = FileOutputStream(croppedImage)
// a bit long running
(Picasso.with(this#MainActivity)
.load(resultUri)
.get()
).compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
Log.d("fileCapturing__", "outputStream: $outputStream")
resultUri = Uri.fromFile(croppedImage)
outputStream.close()
uiThread {
//add to mu list
var mu_list = ArrayList<Uri>(1)
mu_list.add(resultUri)
Log.d("fileCapturing__", "camera uri" + resultUri.toString())
openPreview(mu_list)
}
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
val error: Exception = result.getError()
Log.d("fileCapturing__", "Error: $error")
}
}
}
//preview
fun openPreview(list: MutableList<Uri>) {
val _object = list
val i = Intent(this, typeOfDocument::class.java)
val args = Bundle()
args.putSerializable("ARRAYLIST", _object as java.io.Serializable)
i.putExtra("BUNDLE", args)
startActivity(i)
finish()
}
//get permissions
//Camera
fun get_permissions_camera() {
if (ContextCompat.checkSelfPermission(this#MainActivity, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
MaterialDialog.Builder(this#MainActivity)
.title("Camera permission")
.content("Camera permissions are required for opening Camera")
.negativeText("Cancel")
.onNegative(object : MaterialDialog.SingleButtonCallback {
override fun onClick(dialog: MaterialDialog, which: DialogAction) {
}
})
.positiveText("Give Permissions")
.onPositive(object : MaterialDialog.SingleButtonCallback {
override fun onClick(dialog: MaterialDialog, which: DialogAction) {
getPermissionsUsingDexter_camera(
android.Manifest.permission.CAMERA
)
}
})
.show()
} else {
_openCamera()
}
}
fun getPermissionsUsingDexter_camera(permissionString: String) {
Dexter.withActivity(this)
.withPermissions(
permissionString
).withListener(object : MultiplePermissionsListener {
override fun onPermissionRationaleShouldBeShown(permissions: MutableList<PermissionRequest>?, token: PermissionToken?) {
}
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
if (report!!.areAllPermissionsGranted() == true) {
_openCamera()
Log.d("mess", "permission given")
} else {
Log.d("mess", "permission not granted")
}
}
})
.check()
}
//gallery
fun get_permissions_gallery() {
if (ContextCompat.checkSelfPermission(this#MainActivity, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
MaterialDialog.Builder(this#MainActivity)
.title("Storage permission")
.content("Storage permissions are required for opening the Gallery")
.negativeText("Cancel")
.onNegative(object : MaterialDialog.SingleButtonCallback {
override fun onClick(dialog: MaterialDialog, which: DialogAction) {
}
})
.positiveText("Give Permissions")
.onPositive(object : MaterialDialog.SingleButtonCallback {
override fun onClick(dialog: MaterialDialog, which: DialogAction) {
getPermissionsUsingDexter_gallery(
android.Manifest.permission.READ_EXTERNAL_STORAGE
)
}
})
.show()
} else {
open_selector()
}
}
fun getPermissionsUsingDexter_gallery(permissionString: String) {
Dexter.withActivity(this)
.withPermissions(
permissionString
).withListener(object : MultiplePermissionsListener {
override fun onPermissionRationaleShouldBeShown(permissions: MutableList<PermissionRequest>?, token: PermissionToken?) {
}
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
if (report!!.areAllPermissionsGranted() == true) {
open_selector()
Log.d("mess", "permission given")
} else {
Log.d("mess", "permission not granted")
}
}
})
.check()
}
//file exploer
fun get_permissions_fileExplorer() {
if (ContextCompat.checkSelfPermission(this#MainActivity, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
MaterialDialog.Builder(this#MainActivity)
.title("Storage permission")
.content("Storage access permissions are required for opening File Explorer")
.negativeText("Cancel")
.onNegative(object : MaterialDialog.SingleButtonCallback {
override fun onClick(dialog: MaterialDialog, which: DialogAction) {
}
})
.positiveText("Give Permissions")
.onPositive(object : MaterialDialog.SingleButtonCallback {
override fun onClick(dialog: MaterialDialog, which: DialogAction) {
getPermissionsUsingDexter_fileExplores(
android.Manifest.permission.READ_EXTERNAL_STORAGE
)
}
})
.show()
} else {
openFileSelector()
}
}
fun getPermissionsUsingDexter_fileExplores(permissionString: String) {
Dexter.withActivity(this)
.withPermissions(
permissionString
).withListener(object : MultiplePermissionsListener {
override fun onPermissionRationaleShouldBeShown(permissions: MutableList<PermissionRequest>?, token: PermissionToken?) {
}
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
if (report!!.areAllPermissionsGranted() == true) {
openFileSelector()
Log.d("mess", "permission given")
} else {
Log.d("mess", "permission not granted")
}
}
})
.check()
}
//progress bar
fun showProcessProgress() {
progressDialog = MaterialDialog.Builder(this)
.title("Please Wait")
.content("Converting Pdf to Images")
.progress(true, 0)
.show()
}
}
The error shows when I try to click an image or fetch from the library.
The provider path used is given below:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
</paths>
I have tried changing the path to "/" but it didn't work. The error wasn't showing earlier but the error exists now.
Here is the snapshot of the logs.
All suggestions are accepted. Thanks in advance.

Categories

Resources