Could not upload multiple images into the database - android

I am getting these errors when I am uploading images. The path is storing in database table, But the image folder does not have image.
These are the errors
E/ErrorUtil: Error: /document/primary:DCIM/Camera/20190804_111501.jpg (No such file or directory)
W/System.err: java.io.FileNotFoundException: /document/primary:DCIM/Camera/20190804_111501.jpg (No such file or directory)
Here I shared my code.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == Activity.RESULT_OK
&& null != data) {
if(data.getClipData() != null) {
val count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
for(i in 0..count-1) {
val imageUri : Uri = data.getClipData().getItemAt(i).uri
// getRealPathFromURI(applicationContext,imageUri)
imageUri.let {
Log.d("imageUri",it.toString())
Log.d("imagePath",it.path)
file = File(it.path)
val jj=Gson()
Log.d("fileIS",jj.toJson(file))
fileType = EnumUtils.FileType.IMAGE.value
val name = file!!.name
Log.d("fimenameis",name)
multipartArray!!.add(MultipartBody.Part.createFormData("files[]", file!!.name, RequestBody.create(MediaType.parse(file!!.path.getMimeType()?: ""), file!!)))
val s = Gson()
Log.d("multipartArray",s.toJson(multipartArray).toString())
}
}
//do something with the image (save it to some directory or whatever you need to do with it here)
} else if(data.getData() != null) {
val imagePath = data.getData().getPath();
fileType = EnumUtils.FileType.IMAGE.value
file = File(imagePath)
multipartArray!!.add(MultipartBody.Part.createFormData("files[]", file!!.name, RequestBody.create(MediaType.parse(file!!.path.getMimeType()?: ""), file!!)))
Log.d("imagePath",imagePath.toString())
//do something with the image (save it to some directory or whatever you need to do with it here)
}
}

yes it happen some time due to file path does not get the absolute path and failed to convert it into file
` private fun getRealPathFromURI(contentURI: Uri): String? {
val result: String?
val cursor = contentResolver.query(contentURI, null, null, null, null)
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.path
} else {
cursor.moveToFirst()
val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
result = cursor.getString(idx)
cursor.close()
}
return result
}`
val file: File = File(getRealPathFromURI(Uri.parse(imagePath)))

Related

how to preview video and upload that video file to firebase in android kotlin

I am trying to upload a video file to firebase.:-
this is the code:-
lateinit var file: Any
private fun selectingVideo() {
val videoPickIntent = Intent(Intent.ACTION_PICK)
videoPickIntent.type = "video/*"
startActivityForResult(Intent.createChooser(videoPickIntent, "Please pick a video"), videoRequest )
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == videoRequest && resultCode == Activity.RESULT_OK && null != data) {
feedImageSelect.visibility = View.GONE
feedVideoSelect.visibility = View.VISIBLE
val pickedVideoUrl = getRealPathFromUri(applicationContext, data.data!!)
file = pickedVideoUrl
feedVideoSelect.setVideoPath(pickedVideoUrl)
// Default Media-Controller
feedVideoSelect.setMediaController(MediaController(this))
// start playing
feedVideoSelect.start()
}
}
// Retrieve Video Path from URI.
private fun getRealPathFromUri(context: Context, contentUri: Uri): String {
var cursor: Cursor? = null
try {
val proj = arrayOf(MediaStore.Images.Media.DATA)
cursor = context.contentResolver.query(contentUri, proj, null, null, null)
val columnIndex = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
return cursor.getString(columnIndex)
} finally {
cursor?.close()
}
}
I am getting this as the error.:-
java.lang.ClassCastException: java.lang.String cannot be cast to android.net.Uri
I have tried all the possible ways to solve it. But Still I am getting this error. I tried other methods as well still they are not working for my requirements.
Make these changes to the code:-
val pickedVideoUrl = data.data
feedVideoSelect.setVideoPath(pickedVideoUrl.toString())

Image is very compressed when saved to firestore

I am opening my phones camera, taking a photo, showing a 50px snippet then saving an image into FirebaseFireStore Storage.
The image is very pixelated when I download it from FireStore. Can someone have a look at my code to see were I am going wrong please?
Perhaps I am saving the 50px image, whereas I would like to save the image that was taken from the camera.
Variable
val REQUEST_CODECAM = 200
var bitmapPhoto: Bitmap? = null
Open the Camera
binding!!.galleryContainer.setOnClickListener { v: View? ->
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, REQUEST_CODECAM)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODECAM && data != null){
bitmapPhoto = data.extras?.get("data") as Bitmap
// Image is shown in 50px ListView cell
binding!!.issueImage.setImageBitmap(data.extras?.get("data") as Bitmap)
//imageUri = data.data
//Picasso.get().load(imageUri).into(binding!!.issueImage)
}
}
Save Button Pressed...
fun saveImage(action: GenericAction?) {
val imageName = UUID.randomUUID().toString()
val imageReference = FirebaseStorage.getInstance().reference.child("partInfoImagesFolder").child(imageName)
val baos = ByteArrayOutputStream()
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val data = baos.toByteArray()
var uploadTask = imageReference.putBytes(data)
uploadTask.addOnFailureListener {
// Handle unsuccessful uploads
}.addOnSuccessListener { taskSnapshot ->
// taskSnapshot.metadata contains file metadata such as size, content-type, etc.
// ...
imageReference.downloadUrl.addOnCompleteListener { task1: Task<Uri?>? ->
if (task1 != null) {
if (task1.isSuccessful()) {
saveCollOfURLString = task1.getResult().toString()
action?.onCallback()
}
}
}
}
}

I can't delete the folder's content from path

I'm currently getting this path from my FileExplorer
val path = "content://com.android.externalstorage.documents/tree/primary:Download"
And I'm trying to delete the content of this location:
val fileFolder = File(path)
deleteFolderContent(fileFolder)
private fun deleteFolderContent(fileFolder: File) {
val files = fileFolder.listFiles()
if (files.isNullOrEmpty()) {
return
} else {
for (file in files) {
file.delete()
}
}
}
But files is always null and I can't delete the content. What am I doing wrong? Can anyone help me? Thanks.
Update:
For obtain this "path" I did this:
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
startActivityForResult(intent, SELECT_FOLDER_REQUEST_CODE)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == SELECT_FOLDER_REQUEST_CODE && resultCode == RESULT_OK) {
val uriTree = data?.data
}
}
you can't access content directory as a File (even when URI points on local storage). check out Providers and ContentResolver, HERE you have some basics, for files there is special one: FileProvider. but for your case ContentResolver may fit for your needs best, with method:
context.contentResolver.delete(uriToDelete, null, null)

How to fix my errors at okHttp3 webscocket android?

I receive such error at my websocket:
Error: [okio.RealBufferedSource.require(RealBufferedSource.kt:201), okio.RealBufferedSource.readByte(RealBufferedSource.kt:210), okhttp3.internal.ws.WebSocketReader.readHeader(WebSocketReader.kt:119), okhttp3.internal.ws.WebSocketReader.processNextFrame(WebSocketReader.kt:102), okhttp3.internal.ws.RealWebSocket.loopReader(RealWebSocket.kt:293), okhttp3.internal.ws.RealWebSocket$connect$1.onResponse(RealWebSocket.kt:195), okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:504), java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162), java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636), java.lang.Thread.run(Thread.java:764)]
It happens when I try to send chunked string files to server. For example when I send file in string with size 14B everything goes well, but when I send file up to 10kB I receive such error. When I try to send chunked 120kB file I receive such error:
Error: [okio.RealBufferedSource.require(RealBufferedSource.kt:201), okio.RealBufferedSource.readByte(RealBufferedSource.kt:210), okhttp3.internal.ws.WebSocketReader.readHeader(WebSocketReader.kt:119), okhttp3.internal.ws.WebSocketReader.processNextFrame(WebSocketReader.kt:102), okhttp3.internal.ws.RealWebSocket.loopReader(RealWebSocket.kt:293), okhttp3.internal.ws.RealWebSocket$connect$1.onResponse(RealWebSocket.kt:195), okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:504), java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162), java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636), java.lang.Thread.run(Thread.java:764)]
Place where I send file:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when {
requestCode == 1 && resultCode == Activity.RESULT_OK -> {
if (data != null) {
val fileUri = data.data!!
val partSize = 10000
val fileString = readTextFile(fileUri)
var name = ""
var size: Long? = null
fileUri.let { returnUri ->
contentResolver.query(returnUri, null, null, null, null)
}?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
cursor.moveToFirst()
name = cursor.getString(nameIndex)
size = cursor.getLong(sizeIndex)
}
if (size!! <= partSize) {
ws.send(ChatRequestMessages.sendFile(fileString!!,
name,
selectedContactId.toString(),
size!!,
0))
} else {
val partsCount = if (size!!.rem(partSize).toInt() == 0) {
size!!.div(partSize)
} else {
size!!.div(partSize)
}
for (currentPart in 0..size!!.div(partSize)) {
val slicedString = if ((currentPart + 1) * partSize <= size!!.toInt()) {
fileString!!.substring(currentPart.toInt() * partSize..(currentPart + 1).toInt() * partSize)
} else {
fileString!!.substring(currentPart.toInt() * partSize until fileString.length)
}
Timber.i("${fileString.length.toLong()} ${currentPart * partSize} ${slicedString.length} $slicedString $name")
ws.send(ChatRequestMessages.sendFile(slicedString,
name,
selectedContactId.toString(),
fileString.length.toLong(),
(currentPart * partSize).toInt()))
}
}
}
}
}
I don't understand why it doesn't happen with small files and how to solve these errors :(
It looks like an empty response. The javadoc from RealBufferedSource.require says Returns when the buffer contains at least byteCount bytes. Throws an
[java.io.EOFException] if the source is exhausted before the required bytes can be read.
okhttp.internal.ws.WebSocketReader tries to read the first byte from the response, but doesn't get it.

URI from Intent.ACTION_GET_CONTENT into File

Launch photo picker using Intent.ACTION_GET_CONTENT
Retrieve URI of selected item
Retrieve PATH of URI so that I can POST it to my webserver
Code to launch browse
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, BROWSE_IMAGE_REQUEST_CODE);
Code to retrieve selected image
if (RESULT_OK == resultCode &&
BROWSE_IMAGE_REQUEST_CODE == requestCode) {
Uri uri = data.getData();
Code to send to the webserver
File file = new File(uri.getPath());
new FileSystemResourceFile(file);
I am currently able to retrieve the PATH from the URI no prob /external/images/media/24 but for some weird reason file is always null, help please?
I've done this method to convert Uri from Intent.ACTION_GET_CONTENT to real path:
public static String getRealPathFromUri(Activity activity, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Which in turn converted into File:
Uri filePathFromActivity = (Uri) extras.get(Intent.EXTRA_STREAM);
filePathFromActivity = Uri.parse(FileUtil.getRealPathFromUri( (Activity) IntentActivity.this, filePathFromActivity));
File imageFile = new File(filePathFromActivity.getPath());
I know its been a long time since the answer, but I faced the same wall and this is the solution I ended up with. The main benefit of this code is that avoids having parametrized (and hard-coded) all possible providers types and locations across all different android versions.
val act = getActivity() as Activity
object: AsyncTask<Uri, Void, File?>() {
override fun doInBackground(uris: Array<Uri>): File? {
if(act.isFinishing()) return null
try {
val dir = act.getCacheDir()
val file = File.createTempFile("PREFIX", "SUFFIX", dir)
val inputStream = act.getContentResolver().openInputStream(uris[0])
val fos = FileOutputStream(file)
BitmapFactory.decodeStream(inputStream)
.compress(Bitmap.CompressFormat.JPEG, 90, fos)
return file
} catch(e: Exception) { e.printStackTrace() }
return null
}
override fun onPostExecute(result: File?) {
result?.let { doSomethingWithFile(it) }
}
}.execute(uri)
I put it wrapped inside of an AsyncTask for the purpose of leaving unblocked ui thread during bitmap compress. Please be aware that using Bitmap.CompressFormat.JPEG means lossing alpha channel.
Hope it helps!
Pick any file using System File Picker:
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "*/*"
startActivityForResult(intent, 1)
onActivityResult:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
val file = data?.data?.let {
getFileFromUri(requireContext().contentResolver, uri, requireContext().cacheDir)
}
}
}
Get File:
private fun getFileFromUri(contentResolver: ContentResolver, uri: Uri, directory: File): File {
val file =
File.createTempFile("suffix", "prefix", directory)
file.outputStream().use {
contentResolver.openInputStream(uri)?.copyTo(it)
}
return file
}

Categories

Resources