'I am getting this issue, I tried using kotlin coroutines and Async still getting the same Calling this from Your main thread can lead to deadlock,

I also made another class that implements runnable to make a new thread still it's now working, Also tried with Aynctask. At last, I made a view model but still same issue. Anyone, please Help. Here is what I am trying to do

GlobalScope.launch (Dispatchers.IO){

                uploadFileToGDrive("/storage/emulated/0/Download/Ticket.pdf",this@AddPost)
                withContext(Dispatchers.Main){
                    Toast.makeText(this@AddPost,"I have gone Mad",Toast.LENGTH_LONG).show()
                
            }

        }



fun createFile (filePath:String):String{
        var file:File=File(filePath)
        val gfile = com.google.api.services.drive.model.File()
        gfile.setName(file.name)
        var mediaContent:FileContent= FileContent("application/pdf",file)
        try {
            var myFile= mDrive?.files()?.create(gfile,mediaContent)?.execute()
            var listOfPermission: MutableList<com.google.api.services.drive.model.Permission>? =myFile!!.permissions
            if(listOfPermission!=null){
                for (per in listOfPermission){
//                    Toast.makeText(this,per.toString(),Toast.LENGTH_LONG).show()
                }
            }
//            Toast.makeText(this,"Uploaded Files",Toast.LENGTH_SHORT).show()
            return  myFile!!.id
        }
        catch (e:Exception){
//            Toast.makeText(this,"Some Error Occured in Uploading Files"+e.toString(),Toast.LENGTH_SHORT).show()
        }
        return "Failed"
    }

I am running this function on a button click in an activity tried all the methods from coroutines to Aync and making new thread still getting the same issue. You can see the Exception



Solution 1:[1]

Don't use GlobalScope, instead use lifeCycleScope. This might resolve the issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prasanna Kumar