My addOnSuccessListener is not showing taskSnapshot Override Option,
here is my codes:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode==CAMERA_REQUEST_CODE && resultCode== Activity.RESULT_OK){
pdialog.setMessage("Uploading")
pdialog.show()
val g = data!!.data
val hh = FirebaseStorage.getInstance().getReference().child("camera").child("pics"+g.lastPathSegment)
hh.putFile(g).addOnSuccessListener {
pdialog.dismiss()
Toast.makeText(this,"upload Done",Toast.LENGTH_LONG).show()
}.addOnFailureListener {
Toast.makeText(this,"Error..pls try again",Toast.LENGTH_LONG).show()
}
}
}
how do I retrieve images from firebase server ?
The UploadTask.TaskSnapshot is available as shown below:
hh.putFile(g).addOnSuccessListener { taskSnapshot ->
pdialog.dismiss()
Toast.makeText(this,"upload Done",Toast.LENGTH_LONG).show()
val uri = taskSnapshot.downloadUrl
}
Related
I am currently trying to learn from a step-by-step tutorial to upload an Image or File to my server while using Volley. This tutorial is a little bit outdated and I really don't understand how I can fix these issues.
the tutorial
onActivityResult(Int, Int, Intent?): Unit' is deprecated. Deprecated in Java
Fragment is attempting to registerForActivityResult after being created. Fragments must call registerForActivityResult() before they are created (i.e. initialization, onAttach(), or onCreate()).
My code
//Uploading Photos
private fun launchGallery() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// There are no request codes
val data: Intent? = result.data
}
}
}
private fun uploadImage() {
imageData?: return
val request = object : VolleyFileUploadRequest(
Request.Method.POST,
postURL,
{
println("response is: $it")
},
{
println("error is: $it")
}
) {
override fun getByteData(): MutableMap<String, FileDataPart> {
var params = HashMap<String, FileDataPart>()
params["imageFile"] = FileDataPart("image", imageData!!, "jpeg")
return params
}
}
Volley.newRequestQueue(requireContext()).add(request)
}
#Throws(IOException::class)
private fun createImageData(uri: Uri) {
val inputStream = requireContext().contentResolver.openInputStream(uri)
inputStream?.buffered()?.use {
imageData = it.readBytes()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE) {
val uri = data?.data
if (uri != null) {
imageView.setImageURI(uri)
createImageData(uri)
}
}
super.onActivityResult(requestCode, resultCode, data)
}
}
you are trying to registerForActivityResult from a method "launchGallery()" which is not the way it should be done, "registerForActivityResult" should be initialized in the Activity/Fragment onCreate function and then you can use the "resultLauncher" variable to open the gallery/camera etc...
also when you are using the "registerForActivityResult" you don't need to override "onActivityResult" (which is now deprecated).
check the Activity Result Api to get a better understanding of how the new api works.
and here is a good tutorial that shows you how to use the Android Activity Result API for selecting and taking images
I can scan a barcode successfully but I somehow cannot get the result. I found out that since I am calling the barcode scanner in a fragment, I need change my code to use this:
class AddIerFragment : Fragment() { ....
val intentIntegrator = IntentIntegrator.forFragment(this)
....
}
The problem is, the "this" keyword is not allowed because it gives me an error of
Type mismatch
Requred: Fragment
Found AddIerFragment
See image below.
I have this code in the fragment
companion object {
#JvmStatic
fun newInstance(param1: String, param2: String) =
AddIerFragment().apply {
arguments = Bundle().apply {
}
}
private const val CAMERA = 1
private const val GALLERY = 2
private const val SCAN = 3
}
R.id.button_atgScan -> {
Dexter.withContext(context!!).withPermissions(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
)
.withListener(object: MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
report?.let{
if(report!!.areAllPermissionsGranted()) {
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES)
intentIntegrator.setPrompt("Scan a barcode")
intentIntegrator.setCameraId(0)
intentIntegrator.setBeepEnabled(false)
intentIntegrator.setBarcodeImageEnabled(true)
intentIntegrator.setOrientationLocked(false)
intentIntegrator.initiateScan()
}
}
}
override fun onPermissionRationaleShouldBeShown(
p0: MutableList<PermissionRequest>?,
p1: PermissionToken?
) {
showRationalDialogForPermission()
}
}).onSameThread().check()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == GALLERY) {
data?.let {
val selectedPhotoUri = data.data
file = File(getPath(selectedPhotoUri))
gView!!.iv_ier_image.setImageURI(selectedPhotoUri)
}
} else if (requestCode == CAMERA) {
data?.extras?.let {
val thumbnail: Bitmap =
data.extras!!.get("data") as Bitmap
file = savebitmap(thumbnail)!!
gView!!.iv_ier_image.setImageBitmap(thumbnail)
}
}
val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (result != null) {
if (result.contents == null) {
Log.i("TAG", "NOTHING")
} else {
Log.i("TAG", result.contents)
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
For support or androidx fragments you should use IntentIntegrator.forSupportFragment(this)
AddIerFragment must not be a subclass of the correct Fragment. At the top of its file, make sure you have imported androidx.fragment.app.Fragment instead of android.app.Fragment. And assuming you're using zxing-android-embedded, make sure you call forSupportFragment, not forFragment.
whate is wrong with this code.
it give me the file with the same size but not supported or corrupted
fun openMusic (activity:Activity,requestcode:Int)
{
val intent= Intent(Intent.ACTION_PICK)
intent.setType("audio/*")
activity.startActivityForResult(intent,requestcode)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
{
super.onActivityResult(requestCode, resultCode, data)
if(requestCode==MUSIC_REQUEST&&resultCode== Activity.RESULT_OK&&data!=null)
{
val output=openFileOutput("hamza11.mp3", Context.MODE_PRIVATE)
val input=contentResolver.openInputStream(data.data)
val bufferreader=BufferedReader(InputStreamReader(input))
val bufferedWriter=BufferedWriter(OutputStreamWriter(output))
var c=bufferreader.read()
do{
bufferedWriter.write(c)
c=bufferreader.read()
}
while(bufferreader.read()>=0)
bufferedWriter.flush()
media= MediaPlayer.create(this,data?.data)
media.start()
}
}
I made permission for write external storage
I am using image picker inside recyclerview
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.tvAnimalType.text = items[position].name
holder.image.setOnClickListener{
requestPermissions(it.context as Activity , arrayOf(WRITE_EXTERNAL_STORAGE),1)
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
(it.context as Activity).startActivityForResult(intent, 1)
}
}
In Main Activity
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
1 -> {/*file front*/
if (resultCode == Activity.RESULT_OK && data != null) {
val selectedImageUri = data.data as Uri
val selectedImageBitmap: Bitmap =
MediaStore.Images.Media.getBitmap(this.contentResolver, selectedImageUri)
}
}
}
}
My question is how to load the selected image in recylerview imageview ?
Try like the following
Pass item position as request_code.
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.tvAnimalType.text = items[position].name
// here you can get image as bitmap using filepath and set in to your image view
val filepath = items[position].filePath
val bitmapImage = ...........[get bitmap from filepath]
holder.image.setImageBitmap(bitmapImage)
holder.image.setOnClickListener{
requestPermissions(it.context as Activity , arrayOf(WRITE_EXTERNAL_STORAGE),1)
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
(it.context as Activity).startActivityForResult(intent, position) // pass position as request code
}
}
And In activity do like the following
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && data != null) {
val selectedImageUri = data.data as Uri
val selectedImageBitmap: Bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, selectedImageUri)
// here you can get image file path using URI
val filePathFromURI = ......[get image path using URI]
// then save it to your list data like
items[requestCode].filePath = filePathFromURI // here items is your data set which passed in adapter from your activity you should replace it with yours.
// now you have to notify your adapter that your data set is changed
adapter.notifyDataSetChanged() // replace adapter with yours.
}
}
}
And one important thing you should have a property named filePath in your data class.
I want to get some info like artist, duration and title from a selected mp3 file.But I seem to get something wrong. I just get some random numbers and that is not what I hoped for. I am thankful for every help I get.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_music)
SelectTrack()
}
private fun SelectTrack() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "audio/mpeg"
startActivityForResult(intent, 0)
}
var selectedTrackUri: Uri? = null
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0 && resultCode == Activity.RESULT_OK && data !=null) {
selectedTrackUri = data.data
val title = MediaMetadataRetriever.METADATA_KEY_TITLE.toString()
val duration = MediaMetadataRetriever.METADATA_KEY_DURATION.toString()
val artist = MediaMetadataRetriever.METADATA_KEY_ARTIST.toString()
AddTrackName_txt.text = title
AddArtistName_txt.text = artist
AddTrackLength_txt.text = duration
//Picasso.get().load(album).into(AddTrackPic_View)
}
}
}
The problem is in the way you retrieve the metadata of the file, you are assigning the values of the keys used to extract the metadata, not reading the actual data from the MediaMetadataRetriever.
Example
private fun selectTrack() {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "audio/mpeg" }
startActivityForResult(intent, RC_MEDIA_FILE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
if (requestCode == RC_MEDIA_FILE && resultCode == Activity.RESULT_OK && intent != null) {
val mmr = MediaMetadataRetriever()
mmr.setDataSource(this, intent.data)
val title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)
val artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
val duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
Log.d("MP3", "title=$title, artist=$artist, duration=$duration")
}
}
companion object {
const val RC_MEDIA_FILE = 100
}
Output
D/MP3: title=Sweet Child O´Mine, artist=Guns N' Roses, duration=356444