File picker doesnt get the path right - kotlin

im using the modern way to get user to pick file and then get it using the "registerForActivityResult(ActivityResultContracts.StartActivityForResult())" method, but the path that I get is not correct (after creating File with the given path it says it doesnt exists). Could anyone please help me with this problem? cant find any solution online with the modern way.
private fun initializeImportResultLauncher() {
importResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val path = result.data!!.data!!.path ?: return#registerForActivityResult
val file = File(path)
val fileExists = file.exists()
binding.importedFileText.text =
String.format("selected file: %s", importFile!!.name)
}
}
}
private fun initializeImportButton() {
binding.importButton.setOnClickListener {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "*/*"
intent.addCategory(Intent.CATEGORY_OPENABLE)
importResultLauncher.launch(intent)
}
}
in the debugger after selecting existing file it says that fileExists is false.
Path in the debugger is: /document/raw:/storage/emulated/0/Download/importFile.csv.
Or maybe im just not correctly saving files in the phone directory, if the code is correct could I get some help with that.
Tried every other method but just cant get it working

Related

Add a PsiElement without adding text to the PsiFile

I'm trying to add a method (PsiMethod) to a class (PsiClass) so that IDEA shows this method when typing. I did this, but I ran into a problem: when I add PsiMethod to PsiClass, the text of this method appears in the file, and I don't need it. I need to add a method so that it is highlighted by IDEA, but it is not displayed in the file as text.
How can this be done?
Here is my code how I add PsiMethod to PsiClass:
val module = ModuleManager.getInstance(project).modules.first()
val file = FilenameIndex
.getFilesByName(
project,
"TestPsiFile.java",
module.moduleContentScope)
.first()
val newMethod = PsiElementFactory.getInstance(project).createMethod("testMethod", PsiType.VOID)
WriteCommandAction.runWriteCommandAction(project) {
file.children
.filter { it.elementType == JavaElementType.CLASS }
.map { it.add(newMethod) }
}
Link to this question in the Jetbrains Community: link

Parsing pdf with Kotlin using a Uri?

I write Kotlin code in Android Studio. The user chooses a file from the phone (I need to access the content as a string). There I get a Uri?. With that Uri? I can extract text from .csv and .txt files:
if (typeOfFile == ".txt" || typeOfFile == ".csv") {
try {
val ins: InputStream? = contentResolver?.openInputStream(uriFromSelectedFile)
val reader = BufferedReader(ins!!.reader())
textIWant = reader.readText()
...
Getting the file type also works fine, but when it comes to opening pdf files, nothing seems to work. I tried using PDFBox from Apache in various ways. The pdf I try to open is a simple onePager and contains only extractable text (can be copied) like this pdf.
This is one of the things I tried, the phone freezes when the file to open is a pdf:
if (typeOfFile == ".pdf") {
try {
val myPDDocument:PDDocument = PDDocument(COSDocument(ScratchFile(File(uriFromSelectedFile.path))))
textIWant = PDFTextStripper().getText(myPDDocument)
...
I´ve been trying for days. Does anyone know, how it works in Kotlin?
It worked using tom_roush.pdfbox and a companion object:
import com.tom_roush.pdfbox.text.PDFTextStripper
class MainActivity : AppCompatActivity() {
companion object PdfParser {
fun parse(fis: InputStream): String {
var content = ""
com.tom_roush.pdfbox.pdmodel.PDDocument.load(fis).use { pdfDocument ->
if (!pdfDocument.isEncrypted) {
content = PDFTextStripper().getText(pdfDocument)
}
}
return content
}
}
Calling the parse function of the companion object:
val fis: InputStream = contentResolver?.openInputStream(uriFromSelectedFile)!!
textIWant = parse(fis)

Kotlin - get Firebase Image DownloadUrl returns "com.google.android.gms.tasks.zzu"

I am trying to upload images to Real time Firebase Database by creating two folders using Compressor library and need to display image like messenger with username but i am unable to display image due to url issue
var filePath = mStorageRef!!.child("chat_profile_images")
.child(userId + ".jpg")
//Create another directory for thumbimages ( smaller, compressed images)
var thumbFilePath = mStorageRef!!.child("chat_profile_images")
.child("thumbs")
.child(userId + ".jpg")
filePath.putFile(resultUri)
.addOnCompleteListener{
task: Task<UploadTask.TaskSnapshot> ->
if (task.isSuccessful) {
//Let's get the pic url
var donwloadUrl = task.result?.storage?.downloadUrl.toString()
Log.d(TAG, "Profilepic link: $donwloadUrl")
//Upload Task
var uploadTask: UploadTask = thumbFilePath
.putBytes(thumbByteArray)
uploadTask.addOnCompleteListener{
task: Task<UploadTask.TaskSnapshot> ->
var thumbUrl = task.getResult()?.storage?.downloadUrl.toString()
Log.d(TAG, "Profilepic link: $thumbUrl")
i tried to change downloadUrl
filepath.downloadUrl.toString
thumbFilePath.downloadUrl.toString
but both these values getting "com.google.android.gms.tasks.zzu"
i also tried to change
task.result.sessionurl.downloadUrl.toString
for this one i am getting downloadUrl but not a complete solution for my problem as still i cannot display image i need to get thumbUrl downloadUrl
You have the exact same and very common misunderstanding as in this question, except it's in java. You should follow the documentation here to understand get getDownloadUrl works. As you can see from the linked API documentation, it's not a property getter, it's actually a method that returns a Task<Uri> that tracks the asynchronous fetch of the URL you want, just like the upload task:
filePath.downloadUrl
.addOnSuccessListener { urlTask ->
// download URL is available here
val url = urlTask.result.toString()
}.addOnFailureListener { e ->
// Handle any errors
}
This will only work after the upload is fully complete.
Correct way of getting download link after uploading
here
Just putting out there, I also encounter the same problem,
but both these values getting "com.google.android.gms.tasks.zzu"
but it wasn't the same mistake from the OP
used addOnCompleteListener instead of addOnSuccesslistener
My Error code:
imageRef.downloadUrl.addOnCompleteListener { url ->
val imageURL = url.toString()
println("imageURL: $imageURL , url: $url")
addUserToDatabase(imageURL)
}

Kotlin enviromental values

I'm learning kotlin, I stumbled across an open-source repo, cloned it and ran on my computer, it is a update tool to update an existing jar, although looking at their code how do they approached to that, they did something like this.
private fun updateJar(frame: LaunchFrame, project: Project) {
val sourcePath = project.jarSourcePath
val jarPath = project.jarPath
val repoName = project.repoName
frame.log("Reading source URL from '$sourcePath'")
val sourceUrl = readTextFile(sourcePath)?.let { URI(it) }
frame.log("Source URL: $sourceUrl")
frame.log("Connecting to GitHub")
val github = GitHub.connectAnonymously()
frame.log("Using repository '$repoName'")
val repo = github.getRepository(repoName)
frame.log("Finding latest release")
val latestRelease = repo.listReleases().first()
val assets = latestRelease.assets
check(assets.size == 1) { "Release must only have one asset" }
val asset = assets.first()
val downloadUrl = URI(asset.browserDownloadUrl)
frame.log("Latest URL: $downloadUrl")
if (sourceUrl == null || sourceUrl != downloadUrl || !verifyJar(jarPath)) {
frame.log("Downloading '$downloadUrl' to '$jarPath'")
downloadFile(downloadUrl, jarPath)
frame.log("Writing '$downloadUrl' to '$sourcePath'")
writeTextFile(sourcePath, downloadUrl.toString())
} else {
frame.log("'$jarPath' is up to date")
}
}
Which looks pretty much straight-forward, but here's the catch, there are no actual URL's for the $sourceUrl and others, can someone shed some light to this question? It starts downloading the repo which is runestar/client but there are no actual links for the exact repo what it's trying to download, so how did they do that?
The values are being extracted using some logic, scattered around various places in the code.
For example, see https://github.com/RuneStar/launcher/blob/3e8dcb59c32d2818c917705c6c4432f9fc12c449/src/main/java/org/runestar/launcher/RuneStar.kt#L15
override val repoName: String get() = "RuneStar/client"
It's not environment variables, and it's not downloading from a URL, it's writing to one on the local filesystem.
The Project interface sets up the file locations and the RuneStar class sets up a specfic Github repository.

Renaming a file in as3 AIR - how to do it if you have file's native path in a var?

The following code is great for renaming a file if you know the file is in applicationStorageDirectory
var sourceFile:File = File.applicationStorageDirectory;
sourceFile = sourceFile.resolvePath("Kalimba.snd");
var destination:File = File.applicationStorageDirectory;
destination = destination.resolvePath("test.snd");
try
{
sourceFile.moveTo(destination, true);
}
catch (error:Error)
{
trace("Error:" + error.message);
}
How do you set the sourceFile if all you have is the file's native path in a string? Like this:
D:\Software\files\testList.db
This throws errors:
sourceFile = sourceFile.resolvePath("D:\Software\files\testList.db");
The idea is I want to rename a file I had previously loaded into a var. I figured I'd extract the native path to a String var, null the File var (so the OS doesn't tell me it can't be renamed while the file is opened in flash), resolve that nativePath as the sourceFile, and use moveTo to rename the file on the hard drive.
Cheers for taking a look.
EDIT:
I've set up a test AIR app with only the following in it:
import flash.events.*;
import flash.filesystem.*;
var original = File.documentsDirectory;
original = original.resolvePath("D:\\Software\\test\\October.db");
var destination:File = File.documentsDirectory;
destination = destination.resolvePath("copy.db");
original.addEventListener(Event.COMPLETE, fileMoveCompleteHandler);
original.addEventListener(IOErrorEvent.IO_ERROR, fileMoveIOErrorEventHandler);
original.moveToAsync(destination);
function fileMoveCompleteHandler(event:Event):void {
trace(event.target); // [object File]
}
function fileMoveIOErrorEventHandler(event:IOErrorEvent):void {
trace("I/O Error.");
}
This fails, as does using D:\Software\test\October.db
I guess what I want to know it - how do you do the resolvePath thing if you already know the full path?
I guess what I want to know it - how do you do the resolvePath thing if you already know the full path?
You don't AFAIK. If your path is actually d:\software\test\october.db you can set a File ref like:
var original:File = new File();
original.nativePath = "d:\software\test\october.db";