How can I extract Info from an selected mp3 file? - android

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

Related

Validation Not Working When Checking If ImageButton Is Empty

Using Kotlin in Android Studio, I created a form where user can fill in necessary details AND click an imageButton to launch the camera, take picture and submit the form. I want to add a validation where the user is prevented from submitting the form if they did not take a photo.
I have tried to validate by using imageButton.drawable == null but it did not display the error toast.
Here are the relevant parts of my codes:
class FormActivity : AppCompatActivity() {
var selectedPhotoUri : Uri? = null
companion object {
const val REQUEST_FROM_CAMERA = 1001
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_artactivity)
...
val imageButton = findViewById<ImageButton>(R.id.imageButton)
// launch camera
imageButton.setOnClickListener {
takePhotoUsingCamera()
}
val submitButton = findViewById<Button>(R.id.submitButton)
submitButton.setOnClickListener {
submitForm(userId.toString(), HRWAnswer, ResultAnswer)
}
}
private fun takePhotoUsingCamera(){
ImagePicker.with(this).cameraOnly()
.crop()
.start(REQUEST_FROM_CAMERA)
}
// to access the image captured
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
when (requestCode){
REQUEST_FROM_CAMERA -> {
selectedPhotoUri = data!!.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
val bitmapDrawable = BitmapDrawable(bitmap)
val imageButton = findViewById<ImageButton>(R.id.imageButton)
imageButton.setImageDrawable(bitmapDrawable)
}
}
}
}
fun submitForm(userId : String, TestOption: String, ResultOption: String){
...
val imageButton = findViewById<ImageButton>(R.id.imageButton)
if (imageButton.drawable == null) {
Toast.makeText(this, "Image of your Test result is required!", Toast.LENGTH_LONG).show()
imageButton.requestFocus()
}
...
}
}
Check this may it helps you.
class FormActivity : AppCompatActivity() {
lateinit var imageButton : ImageButton//HERE YOU NEED TO ADD BUTTON.Dont add buttons initialization multiple time in once class.
var selectedPhotoUri : Uri? = null
companion object {
const val REQUEST_FROM_CAMERA = 1001
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_artactivity)
...
imageButton = findViewById<ImageButton>(R.id.imageButton)
// launch camera
imageButton.setOnClickListener {
takePhotoUsingCamera()
}
val submitButton = findViewById<Button>(R.id.submitButton)
submitButton.setOnClickListener {
submitForm(userId.toString(), HRWAnswer, ResultAnswer)
}
}
private fun takePhotoUsingCamera(){
ImagePicker.with(this).cameraOnly()
.crop()
.start(REQUEST_FROM_CAMERA)
}
// to access the image captured
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
when (requestCode){
REQUEST_FROM_CAMERA -> {
selectedPhotoUri = data!!.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
val bitmapDrawable = BitmapDrawable(bitmap)
val imageButton = findViewById<ImageButton>(R.id.imageButton)
imageButton.setImageDrawable(bitmapDrawable)
}
}
}
}
fun submitForm(userId : String, TestOption: String, ResultOption: String){
...
if (imageButton.drawable == null) {
Toast.makeText(this, "Image of your Test result is required!", Toast.LENGTH_LONG).show()
imageButton.requestFocus()
}
...
}
}
as stated by Mike M. in the comment above, it will never be null due to its drawable set layout. i have changed my approach to achieve my target outcome.

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.

Why does sending data between activities not work?

I am currently using Kotlin. I am trying to change the colour of a box in main activity by going to another activity that is the colour setting activity. My code returns no errors but not working. I tried reading different result on this page but none answering my question. Thank u for your help.
mainactivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button_box = findViewById<Button>(R.id.button_box)
button_box.setOnClickListener {
val intent = Intent(this, boxColor::class.java)
startActivity(intent)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
val returnColor = data!!.getStringExtra("colorName")
val boxColorChoice = when (returnColor) {
"green" -> R.drawable.box_green
"grey" -> R.drawable.box_grey
"lblue" -> R.drawable.box_lblue
"purple" -> R.drawable.box_purple
"red" -> R.drawable.box_red
"white" -> R.drawable.box_white
"yellow" -> R.drawable.box_yellow
else -> R.drawable.box_white
}
button_box.setBackgroundResource(boxColorChoice)
}
}
here is boxcolor.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_box_color)
val green = findViewById<Button>(R.id.green_box)
val red = findViewById<Button>(R.id.red_box)
val white = findViewById<Button>(R.id.white_box)
val yellow = findViewById<Button>(R.id.yellow_box)
val grey = findViewById<Button>(R.id.grey_box)
val lblue = findViewById<Button>(R.id.lblue_box)
green.setOnClickListener {
val intent = Intent()
intent.putExtra("colorName", "green")
setResult(Activity.RESULT_OK, intent)
finish()
}
(and the same onclicklistener for all the other colours)
also I know this is small problem but thank you very much for helping. I am 14 year old boy from rajasthan and I want to be a programmer and learning
you need to use startActivityForResult your code must change to these :
mainactivity.kt
...
val mRequestCode = 101 //ADD THIS LINE
...
button_box.setOnClickListener {
val intent = Intent(this, boxColor::class.java)
startActivityForResult(intent, mRequestCode) //ADD THIS LINE
}
...
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == mRequestCode) { //CHANGE THIS LINE
...
}
}
and in your boxcolor.kt:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_box_color)
val mRequestCode = 101 //ADD THIS LINE
...
green.setOnClickListener {
val intent = Intent()
intent.putExtra("colorName", "green")
setResult(mRequestCode, intent) //CHANGE THIS LINE
finish()
}
(and the same onclicklistener for all the other colours)
Note that don't use Activity.RESULT_OK as requestCode
Please use Request Code and startActivityForResult
Example:
private val RC = 101
val intent = Intent(this, boxColor::class.java)
startActivityForResult(intent, RC)

Use image picker inside recyclerview

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.

Using Kotlin to pass Image from ImageView to another Activity in Android

How to pass Image selected in ImageView to another Activity in Android using Kotlin ?
This is the way to select the Image inside the ImageView using internal Storage and I need to pass the image to another activity
fun Loadimage()
{
var intent = Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent,ImageCode)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode==ImageCode && data!=null && resultCode== Activity.RESULT_OK)
{
val selectedImage = data.data
val filepath = arrayOf(MediaStore.Images.Media.DATA)
val cursor = contentResolver.query(selectedImage,filepath,null,null,null)
cursor.moveToFirst()
val Index = cursor.getColumnIndex(filepath[0])
val Picture = cursor.getString(Index)
cursor.close()
imageView.setImageBitmap(BitmapFactory.decodeFile(Picture))
}
}
You can pass Picture variable to next activity using Intents like below
val intent = Intent(this, NextActivity::class.java)
intent.putExtra("picture", Picture)
startActivity(intent)
Then in NextActivity, in onCreate method, you can get picture using
val Picture = getIntent().getStringExtra("picture")
In the NextActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val postImage = findViewById<ImageView>(R.id.post_image)
myPic = postImage
}
companion object {
lateinit var myPic: ImageView()
}
And in the first Activity:
NextActivity.myPic = Picture

Categories

Resources