saving music to internal storage in android - android

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

Related

How to upload a bitmap with Fast Android Networking

I'm trying to upload a image to a server as taken from camera with FAN. I've tried to convert into PNG and JPEG and encoded to image but adding multipart file it always shows me errors
Here's a fragent of my code while trying.
After taken the photo:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
bitmap = data!!.extras!!["data"] as Bitmap?
encodeBitmap(bitmap)
}
super.onActivityResult(requestCode, resultCode, data)
}
The function to encode bitmap
private fun encodeBitmap(bitmap: Bitmap?){
val byteArrayOutputStream = ByteArrayOutputStream()
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream)
val byteofimages = byteArrayOutputStream.toByteArray()
encodedimage = Base64.encodeToString(byteofimages, Base64.DEFAULT)
confirmarEntrega()
}
And the atempt to upload with FAN
private fun confirmarEntrega(){
val uploadURL ="http://192.168.1.229/sistema.com/API/upload.php"
val requestQueue = Volley.newRequestQueue(this)
val txtNombre = findViewById<TextView>(R.id.txtClientName)
val txtDireccion= findViewById<TextView>(R.id.txtDireccion)
val txtProducto = findViewById<TextView>(R.id.txtProducto)
val txtTelefono = findViewById<TextView>(R.id.txtTelefono)
val scannerTextview = findViewById<TextView>(R.id.scannerTextView)
val btnConfirmar = findViewById<Button>(R.id.btnConfirmar)
progressDialog!!.setMessage("Espere un segundo")
progressDialog!!.show()
AndroidNetworking.upload(uploadURL)
.addMultipartFile("image", encodedimage) //Here's where im lost
.setPriority(Priority.HIGH)
.build()
.setUploadProgressListener(object : UploadProgressListener{
override fun onProgress(bytesUploaded: Long, totalBytes: Long) {
}
})
.getAsJSONObject(object : JSONObjectRequestListener{
override fun onResponse(response: JSONObject?) {
}
override fun onError(anError: ANError?) {
}
})
}

bitmap.sameAs() doesn't work on image comparison from Intent picking

My application checks whether the new selected image is the same as the previous one so that I don't need to update the cloud data, but newBitmap.sameAs(oldBitmap) always return false even though I pick the same photo.
Piece of my code:
private lateinit var oldBitmap: Bitmap
private lateinit var newBitmap: Bitmap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my_profile)
myProfilePictureUrl = intent.getStringExtra("myProfilePictureUrl")!!
if (myProfilePictureUrl.isNotEmpty()) {
Picasso.get().load(myProfilePictureUrl).into(my_profile_imageView)
}
oldBitmap = (my_profile_imageView.drawable as BitmapDrawable).bitmap //for later comparison
my_profile_imageView.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, RESULT_CODE_PICK_IMAGE)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RESULT_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
val inputStream = contentResolver.openInputStream(data!!.data!!)
val bitmap = BitmapFactory.decodeStream(inputStream)
newBitmap = bitmap //for comparison
my_profile_imageView.setImageBitmap(bitmap)
}
}
And when the user click on the "save" button on the action bar will it first check whether they are the same photo:
private fun updateProfile(nickname: String) {
if (this::newBitmap.isInitialized && !newBitmap.sameAs(oldBitmap)) { //here
//upload task code
}
}
THE PROBLEM IS:
!newBitmap.sameAs(oldBitmap) always return false even they are the same photo, may be the problem of PICASSO? Or the way I used to compare is not right. Any help would be appreciated.

how to get gallery image path with an Intent

In my android application, I am trying to let the user select a gallery image and show a high-quality image in another activity. is there a way to get an absolute path from URI? or is there an efficient way to do this?
This function opens the gallery and lets the user select an image:
private fun getGalleryImage() {
val galleryImageIntent =
Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
if (galleryImageIntent.resolveActivity(requireActivity().packageManager) != null) {
startActivityForResult(galleryImageIntent, REQUEST_GALLERY_IMAGE)
}
}
And the following gets the result, but I am not sure how to get the image path
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_GALLERY_IMAGE && resultCode == RESULT_OK) {
startActivity(
Intent(context, ImageViewActivity::class.java).putExtra(
"imagePath",
data?.data?.toString()
)
)
} else
super.onActivityResult(requestCode, resultCode, data)
}
Here is my ImageViewActivity:
class ImageViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_view)
backBtn.setOnClickListener {
finish()
}
val imagePath = intent?.extras?.get("imagePath")
BitmapFactory.decodeFile(imagePath?.toString())?.also { bitmap ->
imageHolder.setImageBitmap(bitmap)
}
}
}
I tried sending the bitmap itself to my ImageViewActivity but it keeps crashing, and from what I read online, it is not possible to send large amount of data to an Activity.

How can I extract Info from an selected mp3 file?

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

Firebase Storage OnsuceessListner in kotlin not showing

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
}

Categories

Resources