I have been trying to use the MLKit to scan a barcode however I don't seem to get anything on return, the info that I'm getting back is
W/libc: Access denied finding property "ro.hardware.chipname"
This is the code that I'm trying, it does enter in the success listener however I doesn't seem to recognize the format.
private fun scanBarcodes(bitmap: Bitmap) {
val options = BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_CODABAR,
Barcode.FORMAT_UPC_A,
Barcode.FORMAT_UPC_E
)
.build()
val scanner = BarcodeScanning.getClient(options)
val image = InputImage.fromBitmap(bitmap, 0)
scanner.process(image)
.addOnSuccessListener { barcodes ->
// It is succesful
for (barcode in barcodes) {
val bounds = barcode.boundingBox
val corners = barcode.cornerPoints
val rawValue = barcode.rawValue
Log.d("RAWVALUE ->>>", rawValue.toString())
when (barcode.valueType) {
Barcode.FORMAT_UPC_A -> {
Log.d("TASK SUCCESFUL ->>>>>>", "UPC A")
val upc = barcode.url
}
Barcode.FORMAT_UPC_E -> {
Log.d("TASK SUCCESFUL ->>>>>>", "UPC E")
}
Barcode.FORMAT_CODABAR -> {
val title = barcode.url!!.title
val url = barcode.url!!.url
}
}
}
}
.addOnFailureListener {
Log.d(TAG, "Problem")
}
}
The BitMap that I'm passing the scanBarcodes function is the one obtained underneath
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 100 && resultCode == RESULT_OK) {
imageUri = data?.data!!
if (binding.switchCamera?.isChecked == true)
Picasso.get()!!.load(imageUri).resize(300, 300).centerCrop()
.into(binding.imageButton)
}
if (requestCode == cameraCode && resultCode == RESULT_OK) {
imageBitmap = data?.extras?.get("data") as Bitmap
val baos = ByteArrayOutputStream()
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
data2 = baos.toByteArray()
val file = File(cacheDir, "filename.jpg")
file.createNewFile()
val fileOS = FileOutputStream(file)
fileOS.write(data2)
fileOS.flush()
fileOS.close()
if (binding.switchCamera?.isChecked == true) {
binding.imageButton.setImageBitmap(imageBitmap)
} else {
scanBarcodes(imageBitmap)
}
}
}
Related
what I want to do is to take a photo with the cellphone en then displays that image in a imageview, but when I did that the image appeared roated 90 degrees. So I searched for solutions to that issue and found that I had to do it this way.
private fun capturePhoto() {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val filePhoto = File(Environment.getExternalStorageDirectory(), "Pic.jpg")
imageUri = FileProvider.getUriForFile(
this#ShowLocationFragment.requireActivity(),
"com.example.countriesapp.provider",
filePhoto
)
path = imageUri.path
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(cameraIntent, REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE) {
if (path != null) {
val inputStream =
this#ShowLocationFragment.requireActivity().contentResolver.openInputStream(
imageUri
)
val ei = inputStream?.let { ExifInterface(it) }
val orientation = ei?.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
val bitmap = getBitmapFromUri()
var rotatedBitmap: Bitmap? = null
rotatedBitmap = when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotateImage(bitmap, 90)
ExifInterface.ORIENTATION_ROTATE_180 -> rotateImage(bitmap, 180)
ExifInterface.ORIENTATION_ROTATE_270 -> rotateImage(bitmap, 270)
else -> bitmap
}
binding.ivPlaceMemory.setImageBitmap(rotatedBitmap)
}
}
}
These are rotateImage and getBitmapFromUri functions
private fun rotateImage(source: Bitmap?, angle: Int): Bitmap? {
if (source == null) return null
val matrix = Matrix()
matrix.postRotate(angle.toFloat())
return Bitmap.createBitmap(
source, 0, 0, source.width, source.height,
matrix, true
)
}
private fun getBitmapFromUri(): Bitmap? {
this#ShowLocationFragment.requireActivity().contentResolver.notifyChange(imageUri, null)
val cr: ContentResolver = this#ShowLocationFragment.requireActivity().contentResolver
val bitmap: Bitmap
return try {
bitmap = MediaStore.Images.Media.getBitmap(cr, imageUri)
bitmap
} catch (e: Exception) {
e.printStackTrace()
null
}
}
However, I'm having this exception
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1331636152, result=-1, data=null} to activity {com.example.countriesapp/com.example.countriesapp.presentation.MainActivity}: java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
Can anybody help to figure out what is going on?
Ive tried to search for solutions but havent found anything that works out.
I want to send the selected images from the gallery to an email. I tried this but when i select email it shows only the text not the attachment so if somebody can help I wil appreciatie
it. (sorry for my bad english)
I'm not 100% sure if that part is written correctly. I want to send ArrayList<Uri?>? to an email
private fun pickImageIntent() {
val intent = Intent()
intent.type = "image/*"
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent, "Select image(s)"), pickimagescode)
}
#Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == pickimagescode) {
if (resultCode == Activity.RESULT_OK) {
if (data!!.clipData != null) {
val count = data.clipData!!.itemCount
for (i in 0 until count) {
val imageUri = data.clipData!!.getItemAt(i).uri
images!!.add(imageUri)
}
pickIImageSwitcher.setImageURI(images!![0])
position = 0
if (previosBtn.isGone || nextBtn.isGone) {
previosBtn.visibility = View.VISIBLE
nextBtn.visibility = View.VISIBLE
} else {
previosBtn.visibility = View.GONE
nextBtn.visibility = View.GONE
}
} else {
val imageUri = data.data
pickIImageSwitcher.setImageURI(imageUri)
position = 0
}
}
}
}
private fun sendMail() {
val recipientList = email.text.toString()
val recipients =
recipientList.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val naamGebruiker = naamGebruiker.text.toString()
val controleur = controleur.text.toString()
val kenteken = kenteken.text.toString()
val datum = datum.text.toString()
val checkKabel = checkKabel.text.toString()
val checkNummerplaten = checkNummerplaten.text.toString()
val checkDieselslot = checkDieselslot.text.toString()
val checkFietsendrager = checkFietsendrager.text.toString()
val checkRijplaten = checkRijplaten.text.toString()
val veld = arrayListOf(
"Naam: $naamGebruiker",
"Controleur: $controleur",
"Kenteken: $kenteken",
"Datum: $datum"
)
val intent = Intent(Intent.ACTION_SEND_MULTIPLE)
intent.putExtra(Intent.EXTRA_SUBJECT, "Uitgifte auto")
intent.putExtra(Intent.EXTRA_EMAIL, recipients)
val sb = StringBuilder()
for (a in veld) {
sb.append(a)
sb.append("\n")
}
intent.putExtra(Intent.EXTRA_TEXT, sb.toString())
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, images)
intent.type = "image/*"
intent.type = "mailto/*"
startActivity(Intent.createChooser(intent, "Kies een e-mailclient"))
}
i know this question has been asked several times but everything i can find is only in Java and not very relevant to me...
I'm trying to select a file when i click on a button in my app (images or videos like : /storage/emulated/0/Download/giphy.gif ) and the when the picture or video is selected, i need the path to go inside an edittext.
I have found that code in kotlin for path :
class URIPathHelper {
fun getPath(context: Context, uri: Uri): String? {
val isKitKatorAbove = true
// DocumentProvider
if (isKitKatorAbove && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).toTypedArray()
val type = split[0]
if ("primary".equals(type, ignoreCase = true)) {
return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
}
} else if (isDownloadsDocument(uri)) {
val id = DocumentsContract.getDocumentId(uri)
val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id))
return getDataColumn(context, contentUri, null, null)
} else if (isMediaDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).toTypedArray()
val type = split[0]
var contentUri: Uri? = null
if ("image" == type) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
} else if ("video" == type) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
} else if ("audio" == type) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
val selection = "_id=?"
val selectionArgs = arrayOf(split[1])
return getDataColumn(context, contentUri, selection, selectionArgs)
}
} else if ("content".equals(uri.scheme, ignoreCase = true)) {
return getDataColumn(context, uri, null, null)
} else if ("file".equals(uri.scheme, ignoreCase = true)) {
return uri.path
}
return null
}
fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
var cursor: Cursor? = null
val column = "_data"
val projection = arrayOf(column)
try {
cursor = uri?.let { context.getContentResolver().query(it, projection, selection, selectionArgs,null) }
if (cursor != null && cursor.moveToFirst()) {
val column_index: Int = cursor.getColumnIndexOrThrow(column)
return cursor.getString(column_index)
}
} finally {
if (cursor != null) cursor.close()
}
return null
}
fun isExternalStorageDocument(uri: Uri): Boolean {
return "com.android.externalstorage.documents" == uri.authority
}
fun isDownloadsDocument(uri: Uri): Boolean {
return "com.android.providers.downloads.documents" == uri.authority
}
fun isMediaDocument(uri: Uri): Boolean {
return "com.android.providers.media.documents" == uri.authority
}
}
And this is what i'm trying :
binding.redloader.setOnClickListener {
val uriPathHelper = URIPathHelper()
val filePath: String? = uriPathHelper.getPath(this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
val uri: Uri = Uri.parse(filePath)
val intent = Intent(Intent.ACTION_VIEW)
intent.type = "image/*"
intent.putExtra(Intent.ACTION_VIEW, uri)
startActivity(Intent.createChooser(intent, "Open file"))
binding.redgif.setText(filePath)
}
When I click on the button it automatically chooses the first picture in the storage, and then it opens google picture but I cannot do anything except watch the pictures...
I'm sorry I know they are some stupid things in my code, I think I have something to do with intent but all I see on the internet is calling private void and it is not working for me...
I'm a complete beginner and I really hope someone can help me...
Update with what i'm trying, i think i'm close :
binding.redloader.setOnClickListener {
val uriPathHelper = URIPathHelper()
intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent = Intent.createChooser(intent, "Choose a file")
val resultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
if (data != null) {
val fileUri: Uri? = data.data
Log.i(LOG_TAG, fileUri.toString())
var fileURIPathHelper: String? = null
try {
fileURIPathHelper = uriPathHelper.getPath(this, EXTERNAL_CONTENT_URI)
} catch (e: Exception) {
Log.e(LOG_TAG, "Error: " + e)
Toast.makeText(this, "Error: " + e, Toast.LENGTH_SHORT).show()
}
this.binding.redgif.setText(fileURIPathHelper)
}
}
}
resultLauncher.launch(intent)
}
I solved it ! :)
val resultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
if (data != null) {
val fileUri: Uri? = data.data
Log.i(PackageManagerCompat.LOG_TAG, fileUri.toString())
val contentUri: String?
try {
contentUri = uriPathHelper.getPath(this, fileUri!!)
this.binding.redgif.setText(contentUri)
} catch (e: Exception) {
Log.e(PackageManagerCompat.LOG_TAG, "Error: " + e)
Toast.makeText(this, "Error: " + e, Toast.LENGTH_SHORT).show()
}
}
}
}
binding.redloader.setOnClickListener {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
intent.addCategory(Intent.CATEGORY_OPENABLE)
startActivity(Intent.createChooser(intent, "Open file"))
resultLauncher.launch(intent)
}
I'm selecting the image from my phone gallery and want to upload image on server but my app crash every time i don't know the reason.. i already study many tutorials and Question but i did not understand. please help me.
Here is my code
class profileCreate : AppCompatActivity() {
var context: Context? = null
var imageUri: Uri? = null
var picturePath: String? = null
val url = "https://apps.faizeqamar.website/charity/api/donnor_add"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile_create)
val et_name = findViewById<EditText>(R.id.et_name)
val et_cnic = findViewById<EditText>(R.id.et_cnic)
val et_email = findViewById<EditText>(R.id.et_email)
val et_phon = findViewById<EditText>(R.id.et_phon)
val et_address = findViewById<EditText>(R.id.et_address)
val profile_image = findViewById<ImageView>(R.id.profile_image)
profile_image.setOnClickListener {
checkPermission()
}
val btn_create_profile = findViewById<Button>(R.id.btn_create_profile)
btn_create_profile.setOnClickListener {
imageUpload()
}
}
Volley Code
private fun imageUpload() {
val smr =
SimpleMultiPartRequest(
Request.Method.POST, url,
Response.Listener { response ->
Log.d("Response", response)
Toast.makeText(
applicationContext,
"xyz",
Toast.LENGTH_LONG
).show()
}, Response.ErrorListener { error ->
Toast.makeText(
applicationContext,
error.message,
Toast.LENGTH_LONG
).show()
})
var fname = et_name.text.toString()
var cnic = et_cnic.text.toString()
var email = et_email.text.toString()
var phone = et_phon.text.toString()
var address = et_address.text.toString()
smr.addFile("user_image", picturePath)
smr.addStringParam("fname", fname)
smr.addStringParam("cnic", cnic)
smr.addStringParam("email", email)
smr.addStringParam("phone", phone)
smr.addStringParam("address", address)
val mRequestQueue = Volley.newRequestQueue(applicationContext)
mRequestQueue.add(smr)
}
Pick Image from phone
//*********pick image from phone************
var READIMAGE: Int = 253
fun checkPermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(
this,
android.Manifest.permission.READ_EXTERNAL_STORAGE
) !=
PackageManager.PERMISSION_GRANTED
) {
requestPermissions(
arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),
READIMAGE
)
return
}
}
loadImage()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
READIMAGE -> {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
loadImage()
} else {
Toast.makeText(
applicationContext,
"cannot access your images",
Toast.LENGTH_LONG
).show()
}
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
val PICK_IMAGE_CODE = 123
fun loadImage() {
var intent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
startActivityForResult(intent, PICK_IMAGE_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_IMAGE_CODE && data != null && resultCode == RESULT_OK) {
imageUri = data.data
val filePathColum = arrayOf(MediaStore.Images.Media.DATA)
val cursor = contentResolver.query(imageUri!!, filePathColum, null, null, null)
cursor!!.moveToFirst()
val columnIndex = cursor.getColumnIndex(filePathColum[0])
picturePath = cursor.getString(columnIndex)
cursor.close()
profile_image?.setImageBitmap(BitmapFactory.decodeFile(picturePath))
}
}
}
Encode your image to string and send to the server like sending strings
change your onACtivityresult as below
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
try {
if (requestCode == PICK_IMAGE_CODE && data != null && resultCode == RESULT_OK) {
val contentURI = data!!.data
try {
logBitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, contentURI)
encodedImgString = getStringImage(logBitmap!!)
profile_image!!.setImageBitmap(logBitmap)
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show()
}
}else if (requestCode== IMAGE_CAPTURE_CODE){
img_logo.setImageURI(image_uri)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
here is the getStringImage function
private fun getStringImage(bmp: Bitmap): String {
val baos = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val imageBytes = baos.toByteArray()
return Base64.encodeToString(imageBytes, Base64.DEFAULT)
}
You can send the encodedImgString to the server and decode from there
Below is the code I checked and it did not work.
I did get not url but get "com.google.android.gms.tasks.zzu#ffbfff5"
I think
val url=taskSnapshot.getMetadata()?.getReference()?.getDownloadUrl()?.toString()
should be amended but I dont know how to fix.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == PICK_PROFILE_FROM_ALBUM && resultCode == Activity.RESULT_OK) {
var imageUri = data?.data
val uid = FirebaseAuth.getInstance().currentUser!!.uid
FirebaseStorage
.getInstance()
.reference
.child("userProfileImages")
.child(uid)
.putFile(imageUri!!)
.addOnSuccessListener { taskSnapshot ->
val url = taskSnapshot.getMetadata()?.getReference()?.getDownloadUrl()?.toString()
val map = HashMap<String, Any>()
map["image"] = url
FirebaseFirestore.getInstance().collection("profileImages").document(uid).set(map)
}
}
}
}