I got files in device. And i want when click select one file and rename name file. But after rename, file become have not format file. How to rename file ?
fun renameFile(){
var file=listDownloadsFile.get(i).file
var filetwo=File("/storage/emulated/0/Download/",new_name)
var check:Boolean=file.renameTo(filetwo)
if(check){
Log.d("kkdkdk",check.toString())
}
else{
Log.d("kkdkdk",check.toString())
}
}
private fun getAllFileInDownload() {
var listDownloadsFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.listFiles()
for (i in 0 until files.size) {
listDownloads.add(
FileData(
files[i],
false
)
)
}
} ```
you can try this:
fun renameFile(){
var file = listDownloadsFile.get(i).file
val oldName = file.nameWithoutExtension
val newPath = file.path.replace(oldName, new_name).trim()
val filetwo = File(newPath)
if (filetwo.exists()) {
//show a message file exited
} else {
val check = renameFile(file, filetwo)
if(check){
Log.d("kkdkdk",check.toString())
}
else{
Log.d("kkdkdk",check.toString())
}
}
}
private fun rename(from: File, to: File): Boolean {
return from.parentFile.exists() && from.exists() && from.renameTo(to)
}
Related
private val listmp3 = ArrayList<String>()
private fun loadmp3() {
val YourFolderPath = Environment.getExternalStorageDirectory().path + "/ieltsTest/"
val file = File(YourFolderPath)
if (file.isDirectory) {
val files = file.listFiles()
if (files != null && files.size > 0) {
for (f in files) {
if (f.isDirectory) {
loadmp3(f.absolutePath)
} else {
for (i in extensions.indices) {
if (f.absolutePath.endsWith(extensions[i])) {
listmp3.add(f.absolutePath)
}
}
}
}
}
}
Log.i("audioList", listmp3.toString())
}
Here, I want to list all the .mp3 in by the specific folder. I am trying to get list of the .mp3 folder. Can any body help me to get list of audio
thanks is advance............
I want rename file and when use bellow code and rename file successful but after I don't see that file on my phone and the file is deleted. I requested 2 permissions READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE successful
My code to get all image in device and rename function
MainActivity{
getAllImages()
btn_rename.setOnClickListener{
var old_file=listImageFile.get(pos_selected)
var new_file=File(old_file.parent,new_name)
var check:Boolean=old_file.renameTo(new_file)
if(check){
// check return true
}
}
}
fun getAllImages() {
listImageFile= arrayListOf()
val allImages = arrayListOf<Uri>()
val imageProjection = arrayOf(
MediaStore.Images.Media.DATA,
)
val cursor = requireActivity().contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
imageProjection,
null,
null
)
cursor.use {
if (cursor != null) {
val data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
while (cursor.moveToNext()) {
var path = cursor.getString(data)
var file=File(path)
if(file.exists()){
listImageFile.add(
FileData(
file,
false
)
)
}
}
}
}
}
Whenever you create/rename/delete file, you must refresh the system files.
Try this below solution after rename the file:
btn_rename.setOnClickListener{
var old_file=listImageFile.get(pos_selected)
var new_file=File(old_file.parent,new_name)
var check:Boolean=old_file.renameTo(new_file)
if(check){
// check return true
MediaScannerConnection.scanFile(context, arrayOf(old_file.absolutePath),null,null)
MediaScannerConnection.scanFile(context, arrayOf(new_file.absolutePath),null,null)
}
}
I'm picking a file from the gallery and copying it to a specified folder. While copying I'm showing a ProgressDialog, I'm doing this with AsyncTask.
I'm trying to show the progress of the file being copied with percentage.
How can I get the current progress of the file being copied and display it as percentage ???
My code for copy file:
// Copy list file selected
for(i in 0 until arrayListCopyMoveFile.size){
if(arrayListCopyMoveFile.get(i).check){
copyFileOrDirectory(arrayListCopyMoveFile.get(i).file.path,path)
}
}
fun copyFileOrDirectory(srcDir: String?, dstDir: String?) {
try {
val src = File(srcDir)
val dst = File(dstDir, src.name)
if (src.isDirectory) {
val files = src.list()
val filesLength = files.size
for (i in 0 until filesLength) {
val src1 = File(src, files[i]).path
val dst1 = dst.path
copyFileOrDirectory(src1, dst1)
}
} else {
copyFile(src, dst)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
#Throws(IOException::class)
fun copyFile(sourceFile: File?, destFile: File) {
if (!destFile.parentFile.exists()) destFile.parentFile.mkdirs()
if (!destFile.exists()) {
destFile.createNewFile()
}
var source: FileChannel? = null
var destination: FileChannel? = null
try {
source = FileInputStream(sourceFile).getChannel()
destination = FileOutputStream(destFile).getChannel()
destination.transferFrom(source, 0, source.size())
} finally {
if (source != null) {
source.close()
}
if (destination != null) {
destination.close()
}
}
} ```
I m desperated. I have 16 TextViews. The goal is to take a picture of a prescription. What I want is to extract the right text for every Textview I have. This is my last problem.
Here is the code of taking a photo, create a file, recognize the text and put it in a TextView.
private fun dispatchTakePictureIntent() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Ensure that there's a camera activity to handle the intent
takePictureIntent.resolveActivity(packageManager)?.also {
// Create the File where the photo should go
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
// Error occurred while creating the File
null
}
// Continue only if the File was successfully created
photoFile?.also {
photoURI = FileProvider.getUriForFile(
this,
"com.example.android.fileprovider2",
it
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO)
/*if (REQUEST_TAKE_PHOTO == 1)
{
return imageView.setImageURI(photoURI)
}*/
}
}
}
}
#Throws(IOException::class)
private fun createImageFile(): File {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
}
}
fun startRecognizing(v: View) {
if (imageView.drawable != null) {
editText.setText("")
v.isEnabled = false
val bitmap = (imageView.drawable as BitmapDrawable).bitmap
val image = FirebaseVisionImage.fromBitmap(bitmap)
val detector = FirebaseVision.getInstance().onDeviceTextRecognizer
detector.processImage(image)
.addOnSuccessListener { firebaseVisionText ->
v.isEnabled = true
processResultText(firebaseVisionText)
}
.addOnFailureListener {
v.isEnabled = true
editText.setText("Failed")
}
} else {
Toast.makeText(this, "Select an Image First", Toast.LENGTH_LONG).show()
}
}
private fun String.toEditable(): Editable = Editable.Factory.getInstance().newEditable(this)
private fun processResultText(resultText: FirebaseVisionText) {
if (resultText.textBlocks.size == 0) {
editText.setText("No Text Found")
return
}
for (blocks in resultText.textBlocks) {
val blockText = blocks.text
val stringText = resultText.text
val stringTextSplit = stringText.lines()
krankenkasse.text = stringTextSplit[1].toEditable()
et2.text = stringTextSplit[4].toEditable()
et3.text = stringTextSplit[5].toEditable()
et4.text = stringTextSplit[6].toEditable()
et5.text = stringTextSplit[7].toEditable()
et6.text = stringTextSplit[8].toEditable()
et7.text = stringTextSplit[9].toEditable()
et8.text = stringTextSplit[11].toEditable()
editText.append(blockText + "\n")
}
}
If you have questions. Please ask.
If you want to detect some specific regions in the image, you could crop the image based on the regions, and send the cropped images into ML Kit.
Another option is to detect the whole image, but filter out texts which are not in the regions. Each detected text has its own bounding box coordinates.
https://firebase.google.com/docs/reference/android/com/google/firebase/ml/vision/text/FirebaseVisionText.TextBlock#getBoundingBox()
In my phone's Storage, There is a file which is "MyFile.sql". There are 200 records at the file. What should I do is to import those 200 records into the app.
First, I just Initialize
llUpdate.setOnClickListener { UpgradeDB(txtUpdate!!).execute("", "", "") }
After that, I start a method, I don't know why It found the file and read already, But it doesn't import to the app. Is this because I write return = null So it didn't import to the app?
override fun doInBackground(vararg params: String): String? {
val filename = "MyFile.sql"
val sdcard = Environment.getExternalStorageDirectory()
val file = File(sdcard, filename)
if (!file.exists()) isCancelled
var dbHelper: MyDBHelper? = null
dbHelper?.writableDatabase.use { db ->
var intTotalLine = 0
var intLine = 1
BufferedReader(FileReader(file)).useLines { _ -> intTotalLine++ }
BufferedReader(FileReader(file)).use { r ->
r.lineSequence().forEach {
if (it.isNotEmpty()) {
db?.execSQL(it)
publishProgress(String.format("Updating %s/%s records", intLine, intTotalLine))
intLine++
}
}
}
}
return null
}
Can you guys Please Help me to check where are the mistakes? Thanks in advance.