Home > Mobile >  Kotlin Timer function and moving to next activity / instance
Kotlin Timer function and moving to next activity / instance

Time:08-19

IM making a trivia application and would like to jump to the next question of the category once the timer is done, at the moment it's jumping back and forth between questions and Im not sure what I've done wrong, can anybody please help me with this?

Link to the video: https://drive.google.com/file/d/1dJLgQ1_hGbOKg4WcuSeeoXzWQb3JoqEY/view?usp=sharing

Here is all the code for it:

package com.example.recognition
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.example.recognition.databinding.ActivityQuestionsBinding
import com.example.recognition.models.Constants.LogoQuestions
import com.example.recognition.models.Constants.getAllCelebQuestions
import com.example.recognition.models.Constants.getMemeQuestions
import com.example.recognition.models.Constants.getMusicQuestions
import com.example.recognition.models.Constants.getTvQuestions
import com.example.recognition.models.Question

class QuestionsActivity : AppCompatActivity() {
    private lateinit var binding: ActivityQuestionsBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityQuestionsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        val username = intent.getStringExtra("username").toString()
        val category = intent.getStringExtra("Category").toString()
        var questionNumber: Int = intent.getIntExtra("number", 0)
        var currentScore = intent.getIntExtra("currentScore", 0)
        Log.i("InitialVals", "$questionNumber,$category,$username,$currentScore")
        Log.i("Category Name", category)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
        actionBar?.hide()

        when (category) {
            "Memes" -> {
                val questions = getMemeQuestions()
                val currQuestion = questions[questionNumber]
                updateUI(username, currQuestion)

                binding.answerOne.setOnClickListener{
                    currentScore  = 1
                    binding.answerOne.setBackgroundColor(Color.parseColor("#64CB40"))
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerTwo.setOnClickListener{
                    binding.answerTwo.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerThree.setOnClickListener{
                    binding.answerThree.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerFour.setOnClickListener{
                    binding.answerFour.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                Log.i("Score", "${currentScore}/${questions.count()}")
            }
            "Music" -> {
                val questions = getMusicQuestions()
                var questionNumber = intent.getIntExtra("number", 0)
                val currQuestion = questions[questionNumber]
                var currentScore = intent.getIntExtra("currentScore", 0)
                updateUI(username, currQuestion)

                binding.answerOne.setOnClickListener{
                    currentScore  = 1
                    binding.answerOne.setBackgroundColor(Color.parseColor("#64CB40"))
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerTwo.setOnClickListener{
                    binding.answerTwo.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerThree.setOnClickListener{
                    binding.answerThree.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerFour.setOnClickListener{
                    binding.answerFour.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                Log.i("Score", "${currentScore}/${questions.count()}")
            }
            "Movies and Tv" -> {
                val questions = getTvQuestions()
                var questionNumber = intent.getIntExtra("number", 0)
                val currQuestion = questions[questionNumber]
                var currentScore = intent.getIntExtra("currentScore", 0)
                updateUI(username, currQuestion)

                binding.answerThree.setOnClickListener{
                    currentScore  = 1
                    binding.answerThree.setBackgroundColor(Color.parseColor("#64CB40"))
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerTwo.setOnClickListener{
                    binding.answerTwo.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerOne.setOnClickListener{
                    binding.answerOne.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerFour.setOnClickListener{
                    binding.answerFour.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                Log.i("Score", "${currentScore}/${questions.count()}")
            }
            "Celebrities" -> {
                val questions = getAllCelebQuestions()
                var questionNumber = intent.getIntExtra("number", 0)
                val currQuestion = questions[questionNumber]
                var currentScore = intent.getIntExtra("currentScore", 0)
                updateUI(username, currQuestion)

                binding.answerFour.setOnClickListener{
                    currentScore  = 1
                    binding.answerFour.setBackgroundColor(Color.parseColor("#64CB40"))
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerTwo.setOnClickListener{
                    binding.answerTwo.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerThree.setOnClickListener{
                    binding.answerThree.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerOne.setOnClickListener{
                    binding.answerOne.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                Log.i("Score", "${currentScore}/${questions.count()}")
            }
            "Logos" -> {
                val questions = LogoQuestions()
                var questionNumber = intent.getIntExtra("number", 0)
                val currQuestion = questions[questionNumber]
                var currentScore = intent.getIntExtra("currentScore", 0)
                updateUI(username, currQuestion)

                binding.answerTwo.setOnClickListener{
                    currentScore  = 1
                    binding.answerTwo.setBackgroundColor(Color.parseColor("#64CB40"))
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerOne.setOnClickListener{
                    binding.answerOne.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                binding.answerThree.setOnClickListener{
                    binding.answerThree.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                }
                binding.answerFour.setOnClickListener{
                    binding.answerFour.setBackgroundColor(Color.parseColor("#EE3A57"))
                    currentScore  = 0
                    nextActivity(questionNumber,category,username,currentScore, questions)
                }
                Log.i("Score", "${currentScore}/${questions.count()}")
            }
        }
        binding.settingsButton.setOnClickListener{
            val intent = Intent(this, Settings::class.java)
            startActivity(intent)
            finish()
        }

        //TODO: Set up a timer for each Question
        //TODO: ASk Stackoverfloq if anyone knows how I could use this timer to move on the next activity once it's done

            object : CountDownTimer(11000,1000){
                override fun onTick(millisUntilFinished: Long){
                    binding.timerText.text =""   (millisUntilFinished / 1000).toString()
                    if(millisUntilFinished/1000 < 5){
                        binding.timerText.setTextColor(Color.YELLOW)
                        //Hello
                    }
                    if (millisUntilFinished/1000 < 3){
                        binding.timerText.setTextColor(Color.RED)

                    } //else

                        when (category) {
                            "Memes" -> {
                                val questions = getMemeQuestions()
                                val time: String = binding.timerText.text.toString()

                                if(time.toInt() === 0){
                                    nextActivity(questionNumber,category,username,currentScore, questions)
                                    onFinish()
                                }

                            }
                            "Music" -> {
                                val questions = getMusicQuestions()
                                nextActivity(questionNumber,category,username,currentScore, questions)
                            }
                            "Movies and Tv" -> {
                                val questions = getTvQuestions()
                                nextActivity(questionNumber,category,username,currentScore, questions)
                            }
                            "Celebrities" -> {
                                val questions = getAllCelebQuestions()
                                nextActivity(questionNumber,category,username,currentScore, questions)
                            }
                            "Logos" -> {
                                val questions = LogoQuestions()
                                nextActivity(questionNumber,category,username,currentScore, questions)
                            }
                        }
                    }

                override fun onFinish(){
                    binding.timerText.setTextColor(Color.RED)
                    binding.timerText.text = "0"
                    Log.i("Values", "$questionNumber,$category,$username,$currentScore")

                }
            }.start()
        }

    fun nextActivity( questionNumber: Int, category: String, username: String, currentScore: Int, questions: ArrayList<Question> ){
        if(questionNumber 1 == questions.count()){
            val intent = Intent(this, ResultsActivity::class.java)
            intent.putExtra("Category", category)
            intent.putExtra("username", username)
            intent.putExtra("currentScore", currentScore)
            startActivity(intent)
            finish()
        } else{
            val intent = Intent(this, QuestionsActivity::class.java)
            intent.putExtra("number", questionNumber 1)
            intent.putExtra("Category", category)
            intent.putExtra("username", username)
            intent.putExtra("currentScore", currentScore)
            startActivity(intent)
            finish()
        }
    }

    fun updateUI(username: String, currentQuestion: Question, ){
        val category = intent.getStringExtra("Category").toString()
        if(currentQuestion.id == 1){
            binding.nameText.text= "Okay $username, ${currentQuestion.QuestionTxt}"
        } else{
            binding.nameText.text = "${currentQuestion.QuestionTxt}"
        }
        binding.textView.text = "$category"
        binding.imageContainer.setImageResource(currentQuestion.QuestionImg)
        binding.answerOne.text = currentQuestion.OptionOne
        binding.answerTwo.text = currentQuestion.OptionTwo
        binding.answerThree.text = currentQuestion.OptionThree
        binding.answerFour.text = currentQuestion.OptionFour
    }
}

CodePudding user response:

Use courante with timeout -> https://kotlinlang.org/docs/cancellation-and-timeouts.html#asynchronous-timeout-and-resources

runBlocking {
    repeat(100_000) { // Launch 100K coroutines
        launch { 
            var resource: Resource? = null // Not acquired yet
            try {
                withTimeout(60) { // Timeout of 60 ms
                    delay(50) // Delay for 50 ms
                    resource = Resource() // Store a resource to the variable if acquired      
                }
                // We can do something else with the resource here
            } finally {  
                resource?.close() // Release the resource if it was acquired
            }
        }
    }
}

CodePudding user response:

I guess, this is happening in the nextActivity() function, Kindly put the debug point and check when the if and else blocks are getting called. Best of Luck!

  • Related