How can I do the kotlin mediaPlayer shuffle play - kotlin

I am trying to create shuffle mode for the music-player application. The problem is; The sound on my list only plays once and stops when finished. but I want all the sounds on my list to be shuffled and played automatically. I am very new to Android programming, I tried hard but failed. I also tried the setOnCompletionListener {} method but it didn't work. I need help. thanks everyone
here are my sample codes;
class MainActivity : AppCompatActivity() {
var mediaPlayer = MediaPlayer()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val Sound1 = R.raw.sound01
val Sound2 = R.raw.sound02
val Sound3 = R.raw.sound03
val Sound4 = R.raw.sound04
val Sound5 = R.raw.sound05
val soundList = ArrayList<Int>()
soundList.add(Sound1)
soundList.add(Sound2)
soundList.add(Sound3)
soundList.add(Sound4)
soundList.add(Sound5)
shuffleBtn.setOnClickListener {
val randomList = Random.nextInt(soundList.size)
val sound = soundList.get(randomList)
mediaPlayer = MediaPlayer.create(this, sound)
mediaPlayer.start()
}
}
}

Add a completion listener that releases the original player and creates a new one.
If you want to play shuffled, you need a variable to store the shuffled list and remove tracks as you play them so you know when to reshuffle. The way you're picking random sounds, you could play the same sound twice in a row sometimes.
By the way, you can create your list more concisely.
I didn't test this code. Sorry for any errors.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val sounds = listOf(
R.raw.sound01,
R.raw.sound02,
R.raw.sound03,
R.raw.sound04,
R.raw.sound05
)
var shuffledSounds = sounds.shuffled()
fun newTrack() {
if (shuffledSounds.isEmpty()) {
shuffledSounds = sounds.shuffled()
}
val nextSound = shuffledSounds.first()
shuffledSounds = shuffledSounds - nextSound
mediaPlayer = MediaPlayer.create(this, nextSound).apply {
setOnCompletionListener{
it.release()
newTrack()
}
start()
}
}
shuffleBtn.setOnClickListener {
newTrack()
}
}

Related

I have a problem trying to use a getContent to replace the onActivityResult

The problem arises when using the registerForActivityResult, then it gives me an error when trying to make the contract (ActivityResultContacts), although I suppose that this last error derives from the previous error so I will focus on the first problem, that of the registerForActivityResult, I really don't know how to explain the problem itself, so I better leave my code below in case someone wants to take a look and try to help me with the problem, if so, thank you very much in advance.
Have a good day.
private val getContent = registerForActivityResult(ActivityResultContracts.TakePicturePreview()){
bitmap ->
heroBitmap = bitmap
heroImage.setImageBitmap(heroBitmap!!)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.saveButton.setOnClickListener{
val superheroName = binding.heroNameEdit.text.toString()
val alterEgo = binding.alterEgoEdit.text.toString()
val bio = binding.bioEdit.text.toString()
val power = binding.powerBar.rating
val hero = Superhero(superheroName, alterEgo, bio, power)
openDetailActivity(hero)
}
heroImage = binding.heroImage
heroImage.setOnClickListener{
openCamera()
}
}
private fun openCamera() {
getContent.launch(null)
}
private fun openDetailActivity(hero: Superhero){
val intent = Intent(this, DetailActivity::class.java)
intent.putExtra(DetailActivity.HERO_KEY, hero)
intent.putExtra(DetailActivity.BITMAP_KEY, heroBitmap)
startActivity(intent)
}
}

Kotlin Composable: How to return data from a called activity

In my Jetpack Compose project I have two activities: ActivityA and ActivityB. I can pass data from ActivityA to ActivityB easily, as follows:
private fun showContinueDialog(indexSent: Int, messageSent: String){
val intent = Intent(this, ActivityB::class.java)
intent.putExtra("indexSent", indexSent)
intent.putExtra("messageSent", messageSent)
startForResult.launch(intent)
}
and:
private val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val intent = result.data
if (intent != null) {
//I expect to receive data here
}
}
}
In ActivityB I have:
lateinit var intent2: Intent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
.......
intent2 = intent}
#Composable
fun ContinueClicked(indexReturn: Int) {
intent2.putExtra("indexSent", indexReturn)
setResult(Activity.RESULT_OK, intent2)
startActivity(intent2)
this.finish()
}
When ActivityB closes, I expect to receive the result (an Integer) to appear in the ActivityResult block of ActivityA, but it does not happen. How can I return data from ActivityB to the ActivityResult block of ActivityA? Thanks!
I figured it out:
In the second activity, add something like this where the activity terminates:
intent.putExtra("indexSent", 7788)
setResult(Activity.RESULT_OK, intent)
this.finish()

How to pass Firebase Realtime database images from reyclerview to image view in another activity. KOTLIN

I have Firebase Realtime Database images displayed in a reyclerview. When users click that image, I want it to send the image to another activity's IMAGEVIEW and open that activity at the same time.
These are pictures of an example I saw on Youtube
As you can see in the second picture. It sent the data from the recyclerview to the imageview in the activity and opened that activity.
My adapter class
class AbstractAdapter(private val mContext: Context, private val abstractList: ArrayList<Abstract>) :
RecyclerView.Adapter<AbstractAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.abstract_image_view, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.imageView.setOnClickListener {
val intent = Intent(mContext, PreviewActivity::class.java)
intent.putExtra("abstract", abstractList[position].abstract.toString())
mContext.startActivity(intent)
}
holder.download_btn.setOnClickListener { }
Glide.with(mContext)
.load(abstractList[position].abstract)
.into(holder.imageView)
}
override fun getItemCount(): Int {
return abstractList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView: ImageView = itemView.findViewById(R.id.abstractImageView)
val download_btn: Button = itemView.findViewById(R.id.abstractDownloadBtn)
}
companion object {
private const val Tag = "RecyclerView"
}
Activity to receive image
class PreviewActivity : AppCompatActivity() {
private lateinit var previewImage: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_preview)
previewImage = findViewById(R.id.preview_image)
val previewImage: ImageView = findViewById(R.id.preview_image)
val bundle :Bundle? = intent.extras
val preview = bundle!!.getString("abstract")
}
Data model
class Abstract(var abstract: String? = null) {
}
I've tried running this code, but it doesn't show my image in the next activity. The Logcat doesn't give me any error, because according to it my code is running perfectly except that it's not showing the image in the next activity. I must be missing something, but I don't know what it is.
You have to set the image url to ImageView using Glide in second activity like this:
class PreviewActivity : AppCompatActivity() {
private lateinit var previewImage: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_preview)
previewImage = findViewById(R.id.preview_image)
val previewImage: ImageView = findViewById(R.id.preview_image)
val bundle :Bundle? = intent.extras
val preview = bundle!!.getString("abstract")
Glide.with(this)
.load(preview)
.into(previewImage)
}

How I get data from fun onResult to fun onMapReady in kotlin

I use retrofit for get data From API. i will displays data ini the maps. data was successfull get from retrofit, but i found problem get data response to fun onMapReady. i don't know to be it
class HomeMapsActivity : AppCompatActivity(), OnMapReadyCallback,
MapHomeContract.View {
private lateinit var mMap: GoogleMap
lateinit var presenter: MapHomePresenter
lateinit var prefsManager: PrefsManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_maps)
supportActionBar!!.title = "Posisi driver"
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
prefsManager = PrefsManager(this)
presenter = MapHomePresenter(this)
presenter.getAnak(prefsManager.prefsIdUser)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
for (dataAnak in anak) {
// Add a marker in Sydney and move the camera
val sydney = LatLng(-34.0, 151.0)
mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
override fun onResult(dataAnakResponse: AnakResponse) {
dataAnakResponse.anak
}
}
please help
onMapReady() is called when you initially start the Map Activity. You can set the map data in onResult.
override fun onResult(dataAnakResponse: AnakResponse) {
val anak = dataAnakResponse.anak
for (dataAnak in anak) {
// Add a marker in Sydney and move the camera
val sydney = LatLng(-34.0, 151.0)
mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}

How to open same Activity with different data in Android Kotlin?

class FirstActivity : AppCompatActivity() {
companion object{
val USER_KEY="FirstActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
button_firstActivity.setOnClickListener {
val string:String=textView_first.text.toString()
val intent=Intent(this,MainActivity::class.java)
intent.putExtra(USER_KEY,string)
startActivity(intent)
}
}
}
class MainActivity : AppCompatActivity() {
companion object{
val MAINUSERKEY="MainActivity"
var str:String=""
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
str=intent.getStringExtra(FirstActivity.USER_KEY)
textview_main.text=str
button_Run.setOnClickListener {
val edittextstring=editText1.text.toString()
val intent=Intent(this,MainActivity::class.java)
intent.putExtra(MAINUSERKEY,edittextstring)
startActivity(intent)
}
}
}
Hello every one! I am new to Android programming with Kotlin.
I have two activities, suppose A and B. I want to start activity B from A and when B starts, it will display the TextView string of A into TextView_Main.
It is working fine now. I want to start activity B again on clicking button_Run which is on Activity B and passing a string again which I entered in edittext of Activity B. And now it should be displayed on textview of Activity B, when it opens again.
Please help me do this.
The problem is that the edittext string is being stored as an intent extra with name MAINUSERKEY="MainActivityā€¯, which is different from the extra you are currently extracting on your MainActivity, the one with name USER_KEY="FirstActivityā€¯. So I would do something like this to ensure I get the correct string extra:
str = with(intent) {
getStringExtra(FirstActivity.USER_KEY) ?: getStringExtra(MainActivity.MAINUSERKEY) ?: "No string extra was found"
}
it is more clear to startActivity like code below, add this code in ActivityB
companion object{
private const val EXTRA_ MAIN_USERKEY = "EXTRA.MAIN_USERKEY"
fun getIntent(context:Context, userKey:String): Intent
{
val intent = Intent(context,ActivityB::class.java)
intent.putExtra(EXTRA_ MAIN_USERKEY, userKey)
return intent
}
}
and this code in ActivityA:
startActivity(ActivityB.getIntent(this,"some key"))
so every time you start activityB you should pass the string