I want to pick and upload image from gallery with one button in the same time for Firebase. But the first when i clicked the button it picked up image and the second time when i clicked it uploads. How can i fix it that when i clicked it should be go to gallery and save to Firebase Storage
idgir.setOnLongClickListener {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.READ_EXTERNAL_STORAGE
) !=
PackageManager.PERMISSION_GRANTED
) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.READ_EXTERNAL_STORAGE
)
) {
Snackbar.make(
view,
"Permission needed for gallery!",
Snackbar.LENGTH_INDEFINITE
).setAction("Give Permission") {
permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
}.show()
} else {
permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
}
} else {
val intentToGallery =
Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
activityResultLauncher.launch(intentToGallery)
}
val uuid = UUID.randomUUID()
val imageName = "$uuid.jpg"
val reference = storage.reference
val imagereference = reference.child("images").child(imageName)
if (selectedPicture != null) {
imagereference.putFile(selectedPicture!!).addOnSuccessListener {
val uploadPictureReference =
storage.reference.child("images").child(imageName)
uploadPictureReference.downloadUrl.addOnSuccessListener {
private fun registerLauncher() {
activityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
val intentFromResult = result.data
if (intentFromResult != null)
selectedPicture = intentFromResult.data
selectedPicture?.let {
binding.idgir.setImageURI(it)
}
}
}
permissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { result ->
if (result) {
val intentToGallery =
Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
activityResultLauncher.launch(intentToGallery)
} else {
Toast.makeText(this#MainActivity, "Permission needed", Toast.LENGTH_LONG)
.show()
}
}
}
}
Where you are launching gallery to pick image in else block if permission in granted in else check is selectedPicture is null if null than pick image else upload image.
Related
So, I am creating an app, with the goal of turning text to pdf, and saving it to the external storage. After running the app with no errors, I encountered a weird bug, the "Manage External Storage Permission" button was not clickable. After reading the stack overflow posts, it seems like I have wrote the proper functions, but all the examples were in activities, so the problem may be there
Any help?
class CreatePdfFragment : Fragment(R.layout.fragment_create_pdf) {
private lateinit var binding: FragmentCreatePdfBinding
private val STORAGE_PERMISSION_CODE: Int = 100
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentCreatePdfBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btnToPdf.setOnClickListener {
if (checkPermission()) {
Log.d(TAG, "onViewCreated: Permission already granted, create folder")
savePdf()
} else {
Log.d(TAG, "onViewCreated: Permission was not granted, request")
requestPermission()
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.isNotEmpty()) {
val write = grantResults[0] == PackageManager.PERMISSION_GRANTED
val read = grantResults[1] == PackageManager.PERMISSION_GRANTED
if (write && read) {
Log.d(TAG, "onRequestPermissionsResult: External Storage Permission granted")
savePdf()
} else {
Log.d(TAG, "onRequestPermissionsResult: External Storage Permission denied...")
toast("External Storage Permission denied...")
}
}
}
}
private fun savePdf() {
//create object of Document class
val mDoc = Document()
//pdf file name
val mFileName = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(System.currentTimeMillis())
//pdf file path
val mFilePath = Environment.getExternalStorageDirectory().toString() + "/" + mFileName +".pdf"
try {
//create instance of PdfWriter class
PdfWriter.getInstance(mDoc, FileOutputStream(mFilePath))
//open the document for writing
mDoc.open()
//get text from EditText i.e. textEt
val mText = binding.etPdfText.text.toString()
//add author of the document (metadata)
mDoc.addAuthor("Atif Pervaiz")
//add paragraph to the document
mDoc.add(Paragraph(mText))
//close document
mDoc.close()
//show file saved message with file name and path
toast("$mFileName.pdf\nis saved to\n$mFilePath")
}
catch (e: Exception){
//if anything goes wrong causing exception, get and show exception message
toast(e.message.toString())
}
}
private val storageActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
Log.d(TAG, "storageActivityResultLauncher: ")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (Environment.isExternalStorageManager()) {
Log.d(TAG, "storageActivityResultLauncher: ")
savePdf()
} else {
Log.d(TAG, "storageActivityResultLauncher: Manage External Storage Permission is denied...")
toast("Manage External Storage Permission is denied...")
}
} else {
}
}
private fun requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
try {
Log.d(TAG, "requestPermission: try")
val intent = Intent()
intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
val uri = Uri.fromParts("package", this#CreatePdfFragment.requireActivity().packageName, null)
intent.data = uri
storageActivityResultLauncher.launch(intent)
} catch (e: Exception) {
Log.d(TAG, "requestPermission: ", e)
val intent = Intent()
intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
storageActivityResultLauncher.launch(intent)
}
} else {
ActivityCompat.requestPermissions(this#CreatePdfFragment.requireActivity(),
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),
STORAGE_PERMISSION_CODE)
}
}
private fun checkPermission(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Environment.isExternalStorageManager()
} else {
val write = ContextCompat.checkSelfPermission(this#CreatePdfFragment.requireActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
val read = ContextCompat.checkSelfPermission(this#CreatePdfFragment.requireActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
write == PackageManager.PERMISSION_GRANTED && read == PackageManager.PERMISSION_GRANTED
}
}
private fun toast(message: String) {
Toast.makeText(this#CreatePdfFragment.requireActivity(), message, Toast.LENGTH_SHORT).show()
}
}
Please ignore, the permission below was missing
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
i'm trying to capture image in android 11 device but request is keep cancelled. i have added also. still unable to capture image. pick image from gallery is working. image is not storing in Android/data folder.
i have added val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) also still unable to create temp file in storage. please provide any solutions
private fun selectImage() {
imageUtils.createImageFile(applicationContext).let {
viewModel.setFileTempPath(it.absolutePath, "doc_name")
startActivityForResult(imageUtils.captureImage(applicationContext, it), 300)
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
300 -> when (resultCode) {
RESULT_OK -> {
Log.d("tmppath", data?.data.toString())
if (data != null && data.data != null) {
val selectedImage: Bitmap =
imageUtils.getBitmap(data.data, this#TaggingActivity)!!
viewModel.dataModel.selectedImagesArrayList.value.let {
if (it == null) {
viewModel.dataModel.selectedImagesArrayList.value = ArrayList()
}
val a = it
a?.add(
ImageDetailsToUpload(
"",
selectedImage,
Constant.CUSTOMER_GEO_TAG,
viewModel.dataModel.documentName.value,
viewModel.commonModel.currentLocation.value!!
)
)
viewModel.dataModel.selectedImagesArrayList.postValue(a)
}
} else {
if (viewModel.dataModel.tmpPath.value != null) {
imageUtils.getBitmapFromPath(viewModel.dataModel.tmpPath.value)
?.let { selectedImage ->
val a = viewModel.dataModel.selectedImagesArrayList.value
a?.add(
ImageDetailsToUpload(
"",
selectedImage,
Constant.CUSTOMER_GEO_TAG,
viewModel.dataModel.documentName.value,
viewModel.commonModel.currentLocation.value!!
)
)
viewModel.dataModel.selectedImagesArrayList.postValue(a)
} ?: run {
viewModel.commonModel.showToastTextView("Sorry Try Again..!")
}
} else {
viewModel.commonModel.showToastTextView("Sorry Try Again..!")
return
}
}
viewModel.dataModel.tmpPath.value = null
}
RESULT_CANCELED -> {
viewModel.setFileTempPath("", "")
Toast.makeText(this,"cancelled",Toast.LENGTH_LONG).show()
}
}
}
//Intent class
fun getCameraIntent(file: File): Intent {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file))
if (Build.VERSION.SDK_INT >= 24) {
try {
val m =
StrictMode::class.java.getMethod("disableDeathOnFileUriExposure")
m.invoke(null)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
} else {
takePictureIntent.putExtra("return-data", true)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
val pickPhoto = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
val intents: ArrayList<Intent> = arrayListOf()
intents.add(takePictureIntent)
intents.add(pickPhoto)
val chooserIntent = Intent.createChooser(
intents.removeAt(intents.size - 1),
" Document Upload"
)
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(arrayOf<Parcelable>()))
return chooserIntent
}
i need to upload image to php server but i need the image to be at max quality before it would capture and upload a bitmap but i need the image to be clear so i tried this code but cant seem to get it to work.
so basically i need to upload the image stored on this line
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
class capture : AppCompatActivity() {
private val PERMISSION_CODE = 1000;
private val IMAGE_CAPTURE_CODE = 1001
var image_uri: Uri? = null
var bitmap: Bitmap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_capture)
//button click
btn_take_photo.setOnClickListener {
//if system os is Marshmallow or Above, we need to request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
//permission was not enabled
val permission = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//show popup to request permission
requestPermissions(permission, PERMISSION_CODE)
}
else{
//permission already granted
openCamera()
}
}
else{
//system os is < marshmallow
openCamera()
}
}
}
private fun openCamera() {
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "New Picture")
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")
image_uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
//camera intent
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
//called when user presses ALLOW or DENY from Permission Request Popup
when(requestCode){
PERMISSION_CODE -> {
if (grantResults.size > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
//permission from popup was granted
openCamera()
}
else{
//permission from popup was denied
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
//called when image was captured from camera intent
if (resultCode == Activity.RESULT_OK){
val takenImage: Bitmap = BitmapFactory.decodeFile(image_uri.toString())
//set image captured to image view
imgv_capture_image_preview.setImageURI(image_uri)
val url = connection.server_url + "body_pictures.php"
val rq: RequestQueue = Volley.newRequestQueue(this)
val sr = object : StringRequest(Method.POST, url, Response.Listener { response ->
val check: String = response
val checknew = check.replace("\\s".toRegex(), "")
if (checknew == "success") {
Toast.makeText(
this,
"Image uploaded Successful",
Toast.LENGTH_LONG
).show()
} else {
Toast.makeText(
this,
"ERROR image upload failed, " + checknew,
Toast.LENGTH_LONG
).show()
}
}, Response.ErrorListener { error ->
Toast.makeText(
this,
"Server TIME OUT",
Toast.LENGTH_LONG
).show()
}) {
override fun getParams(): MutableMap<String, String> {
val map = HashMap<String, String>()
val images = takenImage?.let { getStringImage(it) }
if (images != null) {
map.put("image_data", images)
}
return map
}
}
rq.add(sr)
}
}
fun getStringImage(bitmap: Bitmap): String? {
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
return Base64.encodeToString(b, Base64.DEFAULT)
}
This is my code :
val btnbymap = mycustomview.findViewById<Button>(R.id.edit_by_map)
btnbymap.setOnClickListener {
if (ContextCompat.checkSelfPermission(
requireContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION
) !=
PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(
requireContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
this.requestPermissions(
arrayOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION
), RequestCode
)
} else {
fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(vl.context)
fusedLocationProviderClient.lastLocation.addOnSuccessListener(requireActivity()) {
if (it != null) {
val latitude: Double = it.latitude
val longitude: Double = it.longitude
val geocoder = Geocoder(this.context, Locale.getDefault())
try {
val address : List<Address> =
geocoder.getFromLocation(latitude, longitude, 1)
val adress1 = address[0].countryName
Toast.makeText(this.context, adress1.toString(), Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Toast.makeText(
this.context,
"can't handle this",
Toast.LENGTH_SHORT
)
.show()
}
} else {
Toast.makeText(context, "can't find location", Toast.LENGTH_SHORT)
.show()
}
}
}
}
}
return vl
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>,
grantResults: IntArray
) {
when (requestCode) {
1 -> {
if (grantResults.isNotEmpty() && grantResults[0] ==
PackageManager.PERMISSION_GRANTED
) {
if ((ContextCompat.checkSelfPermission(
requireContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION
) ==
PackageManager.PERMISSION_GRANTED)
) {
Toast.makeText(context, "Permission Granted", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(context, "Permission Denied", Toast.LENGTH_SHORT).show()
}
return
}
}
}
}
I want use geocoder to get address from LatLngn(Coordinates).
when i use this method (geocoding_reverse) the emulator android studio give me back the address (country name ) but in my real device the catch method give back ( can't handle this ) .
why when i use the emulator the try method worked but in the real device goes to catch method .
where of my codes is wrong ?
how can i handle this ?
tnk's in advancde
I am currently using the following code here:
val cameraRequestCode = 1
val cameraPermissionCode = 1
var imageUri : Uri? = null
#RequiresApi(api = Build.VERSION_CODES.M)
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == cameraRequestCode) {
if (resultCode == Activity.RESULT_OK) {
var stream: FileOutputStream? = null
try {
val photo: Bitmap =
MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
val saveFilePath: String = getRealPathFromURI(imageUri)
stream = FileOutputStream(saveFilePath)
photo.compress(Bitmap.CompressFormat.JPEG, 25, stream)
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(
applicationContext,
"Can't save image !",
Toast.LENGTH_SHORT
).show()
} finally {
try {
if (stream != null) {
stream.close()
Toast.makeText(
applicationContext,
"Image saved successfully !",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
applicationContext,
"Can't save image, try again !",
Toast.LENGTH_SHORT
).show()
}
} catch (e: IOException) {
e.printStackTrace()
}
}
farmersPixImageView.setImageURI(imageUri)
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(applicationContext, "Cancelled", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(applicationContext, "Can't capture image !", Toast.LENGTH_SHORT)
.show()
}
}
}
private fun getRealPathFromURI(contentUri: Uri?): String {
val proj = arrayOf(MediaStore.Images.Media.DATA)
val cursor: Cursor = managedQuery(contentUri, proj, null, null, null)
val column_index: Int = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
return cursor.getString(column_index)
}
#RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
farmersPixImageView.setOnClickListener {
//if system os is Marshmallow or Above, we need to request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED
) {
//permission was not enabled
val permission = arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
//show popup to request permission
requestPermissions(permission, cameraPermissionCode)
} else {
val values = ContentValues()
values.put(
MediaStore.Images.Media.TITLE,
"${relativeFileName}_${System.currentTimeMillis()}"
)
values.put(
MediaStore.Images.Media.DISPLAY_NAME,
"${relativeFileName}_${getDate(
System.currentTimeMillis(),
"MM/dd/yyyy hh:mm:ss.SSS"
)}"
)
values.put(MediaStore.Images.Media.DESCRIPTION, "My Photos")
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
imageUri = contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
val cameraIntent =
Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(cameraIntent, cameraRequestCode)
}
}
}
}
I am using this because I could not get the sample from the Official Documentation to work.
I previously used:
values.put(MediaStore.Images.Media.RELATIVE_PATH, relativeLocation)
but it is only available on Android Q onwards.
I also don't know how to use imageUri to save to custom location because it using contentResolver:
imageUri = contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
How do I save the photo on custom location using the above code?