问:
Android Studio Unable to find explicit activity class although class exists
I'm stuck with some code for school. I followed a tutorial and feel like I have 100% the same (checked multiple times). But still I get an error. Android Studio doesn't show any mistakes.

Thanks a lot for any help!

I get the following error:

```<code>   --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ecosense, PID: 4840
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.ecosense/com.example.ecosense.ResultActivity}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
        at android.app.Activity.startActivityForResult(Activity.java:4586)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
        at android.app.Activity.startActivityForResult(Activity.java:4544)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
        at com.example.ecosense.QuestionActivity.finishGame(QuestionActivity.kt:318)
        at com.example.ecosense.QuestionActivity.access$finishGame(QuestionActivity.kt:44)
        at com.example.ecosense.QuestionActivity$onOptionsItemSelected$2.onClick(QuestionActivity.kt:375)
        at com.afollestad.materialdialogs.MaterialDialog.onClick(MaterialDialog.java:367)
        at android.view.View.performClick(View.java:6597)
        at android.view.View.performClickInternal(View.java:6574)
        at android.view.View.access$3100(View.java:778)
        at android.view.View$PerformClick.run(View.java:25885)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

And this is my QuestionActivity class.

```<code>package com.example.ecosense

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.CountDownTimer
import android.support.constraint.ConstraintLayout
import android.support.design.widget.Snackbar
import android.support.design.widget.NavigationView
import android.support.v4.content.LocalBroadcastManager
import android.support.v4.view.GravityCompat
import android.support.v4.view.ViewPager
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.example.ecosense.Adapter.GridAnswerAdapter
import com.example.ecosense.Adapter.MyFragmentAdapter
import com.example.ecosense.Adapter.QuestionListHelperAdapter
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog
import com.example.ecosense.Common.Common
import com.example.ecosense.Common.SpacesItemDecoration
import com.example.ecosense.DBHelper.DBHelper
import com.example.ecosense.Model.CurrentQuestion
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_question.*
import kotlinx.android.synthetic.main.app_bar_question.*
import kotlinx.android.synthetic.main.content_question.*
import org.w3c.dom.Text
import java.lang.StringBuilder
import java.util.concurrent.TimeUnit

class QuestionActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    val CODE_GET_RESULT = 9999

    lateinit var countDownTimer: CountDownTimer

    var time_play = Common.TOTAL_TIME

    var isAnswerModeView = false

    lateinit var adapter: GridAnswerAdapter

    lateinit var questionHelperAdapter: QuestionListHelperAdapter

    lateinit var txt_wrong_answer: TextView

    internal var goToQuestionNum: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent!!.action!!.toString() == Common.KEY_GO_TO_QUESTION) {
                val question = intent!!.getIntExtra(Common.KEY_GO_TO_QUESTION, -1)
                if (question != -1)
                    view_pager.currentItem = question

                drawer_layout.closeDrawer(Gravity.LEFT)
            }
        }

    }

    override fun onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(goToQuestionNum)
        if (countDownTimer != null)
            countDownTimer!!.cancel()
        if (Common.fragmentList != null)
            Common.fragmentList.clear()
        if (Common.answerSheetList != null)
            Common.answerSheetList.clear()
        super.onDestroy()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_question)
        setSupportActionBar(toolbar)

        LocalBroadcastManager.getInstance(this)
            .registerReceiver(goToQuestionNum, IntentFilter(Common.KEY_GO_TO_QUESTION))

        val toggle = ActionBarDrawerToggle(
            this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
        )
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()

        nav_view.setNavigationItemSelectedListener(this)

        val recycler_helper_answer_sheet =
            nav_view.getHeaderView(0).findViewById<View>(R.id.answer_sheet) as RecyclerView
        recycler_helper_answer_sheet.layoutManager = GridLayoutManager(this, 3)
        recycler_helper_answer_sheet.setHasFixedSize(true)
        recycler_helper_answer_sheet.addItemDecoration(SpacesItemDecoration(2))

        val btn_done = nav_view.getHeaderView(0).findViewById<View>(R.id.btn_done) as Button
        btn_done.setOnClickListener {
            if (!isAnswerModeView)
            {
                MaterialStyledDialog.Builder(this@QuestionActivity)
                    .setTitle("Finish?")
                    .setDescription("Do you really want to finish?")
                    .setIcon(R.drawable.ic_mood_white_24dp)
                    .setNegativeText("No")
                    .onNegative { dialog, which -> dialog.dismiss() }
                    .setPositiveText("Yes")
                    .onPositive { dialog, which -> finishGame()
                     drawer_layout.closeDrawer(Gravity.LEFT)}
                    .show()

            }
            else {
                finishGame()

            }
        }

        //Get Question base on Category
        genQuestion()

        if (Common.questionList.size > 0) {
            //Show Timer, Right Answer text view
            txt_timer.visibility = View.VISIBLE
            txt_right_answer.visibility = View.VISIBLE

            countTimer()

            //Gen item for grid_answer
            genItems()
            grid_answer.setHasFixedSize(true)
            if (Common.questionList.size > 0)
                grid_answer.layoutManager = GridLayoutManager(
                    this,
                    if (Common.questionList.size > 5) Common.questionList.size / 2 else Common.questionList.size
                )
            adapter = GridAnswerAdapter(this, Common.answerSheetList)

            grid_answer.adapter = adapter

            //Gen fragment list
            genFragmentList()

            val fragmentAdapter = MyFragmentAdapter(supportFragmentManager, this, Common.fragmentList)
            view_pager.offscreenPageLimit = Common.questionList.size
            view_pager.adapter = fragmentAdapter // Bind question to View Pager

            sliding_tabs.setupWithViewPager(view_pager)

            //Event
            view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {

                val SCROLLING_RIGHT = 0
                val SCROLLING_LEFT = 1
                val SCROLLING_UNDETERMINED = 2

                var currentScrollDirection = SCROLLING_UNDETERMINED

                private val isScrollDirectionUndetermined: Boolean
                    get() = currentScrollDirection == SCROLLING_UNDETERMINED
                private val isScrollDirectionRight: Boolean
                    get() = currentScrollDirection == SCROLLING_RIGHT
                private val isScrollDirectionLeft: Boolean
                    get() = currentScrollDirection == SCROLLING_LEFT

                private fun setScrollingDirection(positionOffset: Float) {
                    if (1 - positionOffset >= 0.5)
                        this.currentScrollDirection = SCROLLING_RIGHT
                    else if (1 - positionOffset <= 0.5)
                        this.currentScrollDirection = SCROLLING_LEFT

                }

                override fun onPageScrollStateChanged(p0: Int) {
                    if (p0 == ViewPager.SCROLL_STATE_IDLE)
                        this.currentScrollDirection = SCROLLING_UNDETERMINED
                }

                override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
                    if (isScrollDirectionUndetermined)
                        setScrollingDirection(p1)
                }

                override fun onPageSelected(p0: Int) {

                    val questionFragment: QuestionFragment
                    var position = 0
                    if (p0 > 0) {
                        if (isScrollDirectionRight) {
                            questionFragment = Common.fragmentList[p0 - 1]
                            position = p0 - 1
                        } else if (isScrollDirectionLeft) {
                            questionFragment = Common.fragmentList[p0 + 1]
                            position = p0 + 1
                        } else {
                            questionFragment = Common.fragmentList[p0]
                        }
                    } else {
                        questionFragment = Common.fragmentList[0]
                        position = 0
                    }

                    if (Common.answerSheetList[position].type == Common.ANSWER_TYPE.NO_ANSWER) {
                        // If you want to show correct answer, enable it
                        val question_state = questionFragment.selectedAnswer()
                        Common.answerSheetList[position] = question_state
                        adapter.notifyDataSetChanged()
                        questionHelperAdapter.notifyDataSetChanged()

                        countCorrectAnswer()

                        txt_right_answer.text = ("${Common.right_answer_count} / ${Common.questionList.size}")
                        txt_wrong_answer.text = "${Common.wrong_answer_count}"

                        if (question_state.type != Common.ANSWER_TYPE.NO_ANSWER) {
                            questionFragment.showCorrectAnswer()
                            questionFragment.disableAnswer()
                        }
                    }
                }

            })

            txt_right_answer.text = "${Common.right_answer_count}/${Common.questionList.size}"
            questionHelperAdapter = QuestionListHelperAdapter(this, Common.answerSheetList)
            recycler_helper_answer_sheet.adapter = questionHelperAdapter
        }
    }

    private fun countCorrectAnswer() {
        Common.right_answer_count = 0 // Reset
        Common.wrong_answer_count = 0

        for (item in Common.answerSheetList)
            if (item.type == Common.ANSWER_TYPE.RIGHT_ANSWER)
                Common.right_answer_count++
            else if (item.type == Common.ANSWER_TYPE.WRONG_ANSWER)
                Common.wrong_answer_count++
    }

    private fun genFragmentList() {
        for (i in Common.questionList.indices) {
            val bundle = Bundle()
            bundle.putInt("index", i)
            val fragment = QuestionFragment()
            fragment.arguments = bundle

            Common.fragmentList.add(fragment)
        }
    }

    private fun genItems() {
        for (i in Common.questionList.indices)
            Common.answerSheetList.add(CurrentQuestion(i, Common.ANSWER_TYPE.NO_ANSWER)) // No answer for all questions
    }

    private fun countTimer() {
        countDownTimer = object : CountDownTimer(Common.TOTAL_TIME.toLong(), 1000) {
            override fun onFinish() {
                finishGame()
            }

            override fun onTick(interval: Long) {
                txt_timer.text = (java.lang.String.format(
                    "%02d:%02d",
                    TimeUnit.MILLISECONDS.toMinutes(interval),
                    TimeUnit.MILLISECONDS.toSeconds(interval) - TimeUnit.MINUTES.toSeconds(
                        TimeUnit.MILLISECONDS.toMinutes(
                            interval
                        )
                    )
                ))
                time_play -= 1000
            }

        }.start()
    }

    private fun finishGame() {
        val position = view_pager.currentItem
        val questionFragment = Common.fragmentList[position]

        val question_state = questionFragment.selectedAnswer()
        Common.answerSheetList[position] = question_state
        adapter.notifyDataSetChanged()
        questionHelperAdapter.notifyDataSetChanged()

        countCorrectAnswer()

        txt_right_answer.text = ("${Common.right_answer_count} / ${Common.questionList.size}")
        txt_wrong_answer.text = "${Common.wrong_answer_count}"

        if (question_state.type != Common.ANSWER_TYPE.NO_ANSWER) {
            questionFragment.showCorrectAnswer()
            questionFragment.disableAnswer()
        }

        val intent = Intent(this@QuestionActivity, ResultActivity::class.java)
        Common.timer = Common.TOTAL_TIME - time_play
        Common.no_answer_count = Common.questionList.size - (Common.right_answer_count + Common.wrong_answer_count)
        Common.data_question = StringBuilder(Gson().toJson(Common.answerSheetList))

        startActivityForResult(intent, CODE_GET_RESULT)

    }

    private fun genQuestion() {
        Common.questionList = DBHelper.getInstance(this)
            .getQuestionByCategory(Common.selectedCategory!!.id)

        if (Common.questionList.size == 0) {
            MaterialStyledDialog.Builder(this)
                .setTitle("Oppps!")
                .setIcon(R.drawable.ic_sentiment_very_dissatisfied_black_24dp)
                .setDescription("We don't have any question in this ${Common.selectedCategory!!.name} category")
                .setPositiveText("OK")
                .onPositive { dialog, which ->
                    dialog.dismiss()
                    finish()
                }.show()
        }
    }

    override fun onBackPressed() {
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START)
        } else {
            this.finish() // Close this activity when click on back button
            super.onBackPressed()
        }
    }

    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        val item = menu!!.findItem(R.id.menu_wrong_answer)
        val layout = item.actionView as ConstraintLayout
        txt_wrong_answer = layout.findViewById(R.id.txt_wrong_answer) as TextView
        txt_wrong_answer.text = 0.toString()
        return true
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.question, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_done -> {
                if (!isAnswerModeView) {
                    MaterialStyledDialog.Builder(this@QuestionActivity)
                        .setTitle("Finish?")
                        .setDescription("Do you really want to finish?")
                        .setIcon(R.drawable.ic_mood_white_24dp)
                        .setNegativeText("No")
                        .onNegative { dialog, which -> dialog.dismiss() }
                        .setPositiveText("Yes")
                        .onPositive { dialog, which ->
                            finishGame()
                            drawer_layout.closeDrawer(Gravity.LEFT)
                        }.show()

                } else {
                    finishGame()
                }
            }
        }
        return true

    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        when (item.itemId) {
            R.id.nav_home -> {
                // Handle the camera action
            }
            R.id.nav_gallery -> {

            }
            R.id.nav_slideshow -> {

            }
            R.id.nav_tools -> {

            }
            R.id.nav_share -> {

            }
            R.id.nav_send -> {

            }
        }
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CODE_GET_RESULT)
        {
            if (resultCode == Activity.RESULT_OK)
            {
                val action = data!!.getStringExtra("action")
                if (action == null || TextUtils.isEmpty(action))
                {
                    val questionIndex = data.getIntExtra(Common.KEY_BACK_FROM_RESULT, -1)
                    view_pager.currentItem = questionIndex

                    isAnswerModeView = true
                    countDownTimer!!.cancel()

                    txt_wrong_answer.visibility = View.GONE
                    txt_right_answer.visibility = View.GONE
                    txt_timer.visibility = View.GONE
                }
                else
                {
                    if (action.equals("doquizagain"))
                        {
                            view_pager.currentItem = 0
                            isAnswerModeView = false

                        txt_wrong_answer.visibility = View.VISIBLE
                        txt_right_answer.visibility = View.VISIBLE
                        txt_timer.visibility = View.VISIBLE

                        for (i in Common.fragmentList.indices) {
                            Common.fragmentList[i].resetQuestion()
                        }

                        for (i in Common.answerSheetList.indices)
                            Common.answerSheetList[i].type = Common.ANSWER_TYPE.NO_ANSWER

                        adapter.notifyDataSetChanged()
                        questionHelperAdapter.notifyDataSetChanged()

                        countTimer()

                    } else if (action.equals("viewanswer"))
                    {
                        view_pager.currentItem = 0
                        isAnswerModeView = true
                        countDownTimer!!.cancel()

                        txt_wrong_answer.visibility = View.GONE
                        txt_right_answer.visibility = View.GONE
                        txt_timer.visibility = View.GONE

                        for (i in Common.fragmentList.indices)
                        {
                            Common.fragmentList[i].showCorrectAnswer()
                            Common.fragmentList[i].disableAnswer()
                        }
                        }
                    }
                }
            }
    }
}
</code>```

My ResultActivity class:

```<code>package com.example.ecosense

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.widget.GridLayoutManager
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import com.example.ecosense.Adapter.ResultGridAdapter
import com.example.ecosense.Common.Common
import com.example.ecosense.Common.SpacesItemDecoration
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog
import kotlinx.android.synthetic.main.activity_question.*
import kotlinx.android.synthetic.main.activity_result.*
import kotlinx.android.synthetic.main.activity_result.txt_right_answer
import kotlinx.android.synthetic.main.content_question.*
import java.util.concurrent.TimeUnit

class ResultActivity : AppCompatActivity() {

    internal var backToQuestion:BroadcastReceiver = object:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent!!.action!!.toString() == Common.KEY_BACK_FROM_RESULT)
            {
                val questionIndex = intent.getIntExtra(Common.KEY_BACK_FROM_RESULT,-1)
                goBackActivityWithQuestionIndex(questionIndex)
            }
        }

    }

    private fun goBackActivityWithQuestionIndex(questionIndex: Int) {
        val returnIntent = Intent()
        returnIntent.putExtra(Common.KEY_BACK_FROM_RESULT,questionIndex)
        setResult(Activity.RESULT_OK,returnIntent)
        finish()

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_result,menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when(item!!.itemId)
        {
            R.id.menu_do_quiz_again -> doQuizAgain()
            R.id.menu_view_answer -> viewAnswer()
            android.R.id.home -> {
                val intent = Intent(applicationContext,CategoryActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                startActivity(intent) // Go back to category when click on back arrow in result activity
            }
        }
        return true
    }

    private fun viewAnswer() {
        val returnIntent = Intent()
        returnIntent.putExtra("action","viewanswer")
        setResult(Activity.RESULT_OK,returnIntent)
        finish()
    }

    private fun doQuizAgain() {

        MaterialStyledDialog.Builder(this@ResultActivity)
            .setTitle("Do quiz again?")
            .setDescription("Do you really want to delete this data?")
            .setIcon(R.drawable.ic_mood_white_24dp)
            .setNegativeText("No")
            .onNegative { dialog, which -> dialog.dismiss() }
            .setPositiveText("Yes")
            .onPositive { dialog, which ->

                val returnIntent = Intent()
                returnIntent.putExtra("action","doquizagain")
                setResult(Activity.RESULT_OK,returnIntent)
                finish()
            }
            .show()
    }

    override fun onDestroy() {
        LocalBroadcastManager.getInstance(this@ResultActivity)
            .unregisterReceiver(backToQuestion)
        super.onDestroy()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result)

        LocalBroadcastManager.getInstance(this@ResultActivity)
            .registerReceiver(backToQuestion, IntentFilter(Common.KEY_BACK_FROM_RESULT))

        toolbar.title = "Result"
        setSupportActionBar(toolbar)

        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        supportActionBar!!.setDisplayShowHomeEnabled(true)

        //
        txt_timer.text = (java.lang.String.format(
            "%02d:%02d",
            TimeUnit.MILLISECONDS.toMinutes(Common.timer.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(Common.timer.toLong()) - TimeUnit.MINUTES.toSeconds(
                TimeUnit.MILLISECONDS.toMinutes(
                    Common.timer.toLong()
                )
            )
        ))
        txt_right_answer.text = "${Common.right_answer_count}/${Common.questionList.size}"

        btn_filter_total.text = "${Common.questionList.size}"
        btn_filter_total.text = "${Common.right_answer_count}"
        btn_filter_total.text = "${Common.wrong_answer_count}"
        btn_filter_total.text = "${Common.no_answer_count}"

        val percent = Common.right_answer_count*100/Common.questionList.size
        if (percent > 80)
            txt_result.text = "Excellent!"
        else if (percent > 65)
            txt_result.text = "Good!"
        else if (percent > 50)
            txt_result.text = "Fair!"
        else
            txt_result.text = "Bad!"

        // Event Button
        btn_filter_total.setOnClickListener{
            val adapter = ResultGridAdapter(this,Common.answerSheetList)
            recycler_result.adapter = adapter
        }

        btn_filter_no_answer.setOnClickListener{
            Common.answerSheetListFiltered.clear()

            for (currentQuestion in Common.answerSheetList)
                if (currentQuestion.type == Common.ANSWER_TYPE.NO_ANSWER)
                    Common.answerSheetListFiltered.add(currentQuestion)
            val adapter = ResultGridAdapter(this,Common.answerSheetListFiltered)
            recycler_result.adapter = adapter
        }

        btn_filter_wrong.setOnClickListener{
            Common.answerSheetListFiltered.clear()

            for (currentQuestion in Common.answerSheetList)
                if (currentQuestion.type == Common.ANSWER_TYPE.WRONG_ANSWER)
                    Common.answerSheetListFiltered.add(currentQuestion)
            val adapter = ResultGridAdapter(this,Common.answerSheetListFiltered)
            recycler_result.adapter = adapter
        }

        btn_filter_right.setOnClickListener{
            Common.answerSheetListFiltered.clear()

            for (currentQuestion in Common.answerSheetList)
                if (currentQuestion.type == Common.ANSWER_TYPE.RIGHT_ANSWER)
                    Common.answerSheetListFiltered.add(currentQuestion)
            val adapter = ResultGridAdapter(this,Common.answerSheetListFiltered)
            recycler_result.adapter = adapter
        }

        // Set Adapter
        val adapter = ResultGridAdapter(this,Common.answerSheetList)
        recycler_result.setHasFixedSize(true)
        recycler_result.layoutManager = GridLayoutManager(this,4)
        recycler_result.addItemDecoration(SpacesItemDecoration(4))
        recycler_result.adapter = adapter

    }
}
</code>```

答:
So I found the error.. It was in the following code. I used txt_timer instead of txt_time, which resulted in a wrong layout reference...

```<code>        txt_timer.text = (java.lang.String.format(
            "%02d:%02d",
            TimeUnit.MILLISECONDS.toMinutes(Common.timer.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(Common.timer.toLong()) - TimeUnit.MINUTES.toSeconds(
                TimeUnit.MILLISECONDS.toMinutes(
                    Common.timer.toLong()
                )
            )
        ))
</code>```

Correct code:

```<code>        txt_time.text = (java.lang.String.format(
            "%02d:%02d",
            TimeUnit.MILLISECONDS.toMinutes(Common.timer.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(Common.timer.toLong()) - TimeUnit.MINUTES.toSeconds(
                TimeUnit.MILLISECONDS.toMinutes(
                    Common.timer.toLong()
                )
            )
        ))
</code>```

Body:
I'm stuck with some code for school. I followed a tutorial and feel like I have 100% the same (checked multiple times). But still I get an error. Android Studio doesn't show any mistakes.

Thanks a lot for any help!

I get the following error:

   --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ecosense, PID: 4840
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.ecosense/com.example.ecosense.ResultActivity}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
        at android.app.Activity.startActivityForResult(Activity.java:4586)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
        at android.app.Activity.startActivityForResult(Activity.java:4544)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
        at com.example.ecosense.QuestionActivity.finishGame(QuestionActivity.kt:318)
        at com.example.ecosense.QuestionActivity.access$finishGame(QuestionActivity.kt:44)
        at com.example.ecosense.QuestionActivity$onOptionsItemSelected$2.onClick(QuestionActivity.kt:375)
        at com.afollestad.materialdialogs.MaterialDialog.onClick(MaterialDialog.java:367)
        at android.view.View.performClick(View.java:6597)
        at android.view.View.performClickInternal(View.java:6574)
        at android.view.View.access$3100(View.java:778)
        at android.view.View$PerformClick.run(View.java:25885)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

And this is my QuestionActivity class.

package com.example.ecosense

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.CountDownTimer
import android.support.constraint.ConstraintLayout
import android.support.design.widget.Snackbar
import android.support.design.widget.NavigationView
import android.support.v4.content.LocalBroadcastManager
import android.support.v4.view.GravityCompat
import android.support.v4.view.ViewPager
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.example.ecosense.Adapter.GridAnswerAdapter
import com.example.ecosense.Adapter.MyFragmentAdapter
import com.example.ecosense.Adapter.QuestionListHelperAdapter
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog
import com.example.ecosense.Common.Common
import com.example.ecosense.Common.SpacesItemDecoration
import com.example.ecosense.DBHelper.DBHelper
import com.example.ecosense.Model.CurrentQuestion
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_question.*
import kotlinx.android.synthetic.main.app_bar_question.*
import kotlinx.android.synthetic.main.content_question.*
import org.w3c.dom.Text
import java.lang.StringBuilder
import java.util.concurrent.TimeUnit

class QuestionActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    val CODE_GET_RESULT = 9999

    lateinit var countDownTimer: CountDownTimer

    var time_play = Common.TOTAL_TIME

    var isAnswerModeView = false

    lateinit var adapter: GridAnswerAdapter

    lateinit var questionHelperAdapter: QuestionListHelperAdapter

    lateinit var txt_wrong_answer: TextView

    internal var goToQuestionNum: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent!!.action!!.toString() == Common.KEY_GO_TO_QUESTION) {
                val question = intent!!.getIntExtra(Common.KEY_GO_TO_QUESTION, -1)
                if (question != -1)
                    view_pager.currentItem = question

                drawer_layout.closeDrawer(Gravity.LEFT)
            }
        }

    }

    override fun onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(goToQuestionNum)
        if (countDownTimer != null)
            countDownTimer!!.cancel()
        if (Common.fragmentList != null)
            Common.fragmentList.clear()
        if (Common.answerSheetList != null)
            Common.answerSheetList.clear()
        super.onDestroy()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_question)
        setSupportActionBar(toolbar)

        LocalBroadcastManager.getInstance(this)
            .registerReceiver(goToQuestionNum, IntentFilter(Common.KEY_GO_TO_QUESTION))

        val toggle = ActionBarDrawerToggle(
            this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
        )
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()

        nav_view.setNavigationItemSelectedListener(this)

        val recycler_helper_answer_sheet =
            nav_view.getHeaderView(0).findViewById<View>(R.id.answer_sheet) as RecyclerView
        recycler_helper_answer_sheet.layoutManager = GridLayoutManager(this, 3)
        recycler_helper_answer_sheet.setHasFixedSize(true)
        recycler_helper_answer_sheet.addItemDecoration(SpacesItemDecoration(2))

        val btn_done = nav_view.getHeaderView(0).findViewById<View>(R.id.btn_done) as Button
        btn_done.setOnClickListener {
            if (!isAnswerModeView)
            {
                MaterialStyledDialog.Builder(this@QuestionActivity)
                    .setTitle("Finish?")
                    .setDescription("Do you really want to finish?")
                    .setIcon(R.drawable.ic_mood_white_24dp)
                    .setNegativeText("No")
                    .onNegative { dialog, which -> dialog.dismiss() }
                    .setPositiveText("Yes")
                    .onPositive { dialog, which -> finishGame()
                     drawer_layout.closeDrawer(Gravity.LEFT)}
                    .show()

            }
            else {
                finishGame()

            }
        }

        //Get Question base on Category
        genQuestion()

        if (Common.questionList.size > 0) {
            //Show Timer, Right Answer text view
            txt_timer.visibility = View.VISIBLE
            txt_right_answer.visibility = View.VISIBLE

            countTimer()

            //Gen item for grid_answer
            genItems()
            grid_answer.setHasFixedSize(true)
            if (Common.questionList.size > 0)
                grid_answer.layoutManager = GridLayoutManager(
                    this,
                    if (Common.questionList.size > 5) Common.questionList.size / 2 else Common.questionList.size
                )
            adapter = GridAnswerAdapter(this, Common.answerSheetList)

            grid_answer.adapter = adapter

            //Gen fragment list
            genFragmentList()

            val fragmentAdapter = MyFragmentAdapter(supportFragmentManager, this, Common.fragmentList)
            view_pager.offscreenPageLimit = Common.questionList.size
            view_pager.adapter = fragmentAdapter // Bind question to View Pager

            sliding_tabs.setupWithViewPager(view_pager)

            //Event
            view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {

                val SCROLLING_RIGHT = 0
                val SCROLLING_LEFT = 1
                val SCROLLING_UNDETERMINED = 2

                var currentScrollDirection = SCROLLING_UNDETERMINED

                private val isScrollDirectionUndetermined: Boolean
                    get() = currentScrollDirection == SCROLLING_UNDETERMINED
                private val isScrollDirectionRight: Boolean
                    get() = currentScrollDirection == SCROLLING_RIGHT
                private val isScrollDirectionLeft: Boolean
                    get() = currentScrollDirection == SCROLLING_LEFT

                private fun setScrollingDirection(positionOffset: Float) {
                    if (1 - positionOffset >= 0.5)
                        this.currentScrollDirection = SCROLLING_RIGHT
                    else if (1 - positionOffset <= 0.5)
                        this.currentScrollDirection = SCROLLING_LEFT

                }

                override fun onPageScrollStateChanged(p0: Int) {
                    if (p0 == ViewPager.SCROLL_STATE_IDLE)
                        this.currentScrollDirection = SCROLLING_UNDETERMINED
                }

                override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
                    if (isScrollDirectionUndetermined)
                        setScrollingDirection(p1)
                }

                override fun onPageSelected(p0: Int) {

                    val questionFragment: QuestionFragment
                    var position = 0
                    if (p0 > 0) {
                        if (isScrollDirectionRight) {
                            questionFragment = Common.fragmentList[p0 - 1]
                            position = p0 - 1
                        } else if (isScrollDirectionLeft) {
                            questionFragment = Common.fragmentList[p0 + 1]
                            position = p0 + 1
                        } else {
                            questionFragment = Common.fragmentList[p0]
                        }
                    } else {
                        questionFragment = Common.fragmentList[0]
                        position = 0
                    }

                    if (Common.answerSheetList[position].type == Common.ANSWER_TYPE.NO_ANSWER) {
                        // If you want to show correct answer, enable it
                        val question_state = questionFragment.selectedAnswer()
                        Common.answerSheetList[position] = question_state
                        adapter.notifyDataSetChanged()
                        questionHelperAdapter.notifyDataSetChanged()

                        countCorrectAnswer()

                        txt_right_answer.text = ("${Common.right_answer_count} / ${Common.questionList.size}")
                        txt_wrong_answer.text = "${Common.wrong_answer_count}"

                        if (question_state.type != Common.ANSWER_TYPE.NO_ANSWER) {
                            questionFragment.showCorrectAnswer()
                            questionFragment.disableAnswer()
                        }
                    }
                }

            })

            txt_right_answer.text = "${Common.right_answer_count}/${Common.questionList.size}"
            questionHelperAdapter = QuestionListHelperAdapter(this, Common.answerSheetList)
            recycler_helper_answer_sheet.adapter = questionHelperAdapter
        }
    }

    private fun countCorrectAnswer() {
        Common.right_answer_count = 0 // Reset
        Common.wrong_answer_count = 0

        for (item in Common.answerSheetList)
            if (item.type == Common.ANSWER_TYPE.RIGHT_ANSWER)
                Common.right_answer_count++
            else if (item.type == Common.ANSWER_TYPE.WRONG_ANSWER)
                Common.wrong_answer_count++
    }

    private fun genFragmentList() {
        for (i in Common.questionList.indices) {
            val bundle = Bundle()
            bundle.putInt("index", i)
            val fragment = QuestionFragment()
            fragment.arguments = bundle

            Common.fragmentList.add(fragment)
        }
    }

    private fun genItems() {
        for (i in Common.questionList.indices)
            Common.answerSheetList.add(CurrentQuestion(i, Common.ANSWER_TYPE.NO_ANSWER)) // No answer for all questions
    }

    private fun countTimer() {
        countDownTimer = object : CountDownTimer(Common.TOTAL_TIME.toLong(), 1000) {
            override fun onFinish() {
                finishGame()
            }

            override fun onTick(interval: Long) {
                txt_timer.text = (java.lang.String.format(
                    "%02d:%02d",
                    TimeUnit.MILLISECONDS.toMinutes(interval),
                    TimeUnit.MILLISECONDS.toSeconds(interval) - TimeUnit.MINUTES.toSeconds(
                        TimeUnit.MILLISECONDS.toMinutes(
                            interval
                        )
                    )
                ))
                time_play -= 1000
            }

        }.start()
    }

    private fun finishGame() {
        val position = view_pager.currentItem
        val questionFragment = Common.fragmentList[position]

        val question_state = questionFragment.selectedAnswer()
        Common.answerSheetList[position] = question_state
        adapter.notifyDataSetChanged()
        questionHelperAdapter.notifyDataSetChanged()

        countCorrectAnswer()

        txt_right_answer.text = ("${Common.right_answer_count} / ${Common.questionList.size}")
        txt_wrong_answer.text = "${Common.wrong_answer_count}"

        if (question_state.type != Common.ANSWER_TYPE.NO_ANSWER) {
            questionFragment.showCorrectAnswer()
            questionFragment.disableAnswer()
        }

        val intent = Intent(this@QuestionActivity, ResultActivity::class.java)
        Common.timer = Common.TOTAL_TIME - time_play
        Common.no_answer_count = Common.questionList.size - (Common.right_answer_count + Common.wrong_answer_count)
        Common.data_question = StringBuilder(Gson().toJson(Common.answerSheetList))

        startActivityForResult(intent, CODE_GET_RESULT)

    }

    private fun genQuestion() {
        Common.questionList = DBHelper.getInstance(this)
            .getQuestionByCategory(Common.selectedCategory!!.id)

        if (Common.questionList.size == 0) {
            MaterialStyledDialog.Builder(this)
                .setTitle("Oppps!")
                .setIcon(R.drawable.ic_sentiment_very_dissatisfied_black_24dp)
                .setDescription("We don't have any question in this ${Common.selectedCategory!!.name} category")
                .setPositiveText("OK")
                .onPositive { dialog, which ->
                    dialog.dismiss()
                    finish()
                }.show()
        }
    }

    override fun onBackPressed() {
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START)
        } else {
            this.finish() // Close this activity when click on back button
            super.onBackPressed()
        }
    }

    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        val item = menu!!.findItem(R.id.menu_wrong_answer)
        val layout = item.actionView as ConstraintLayout
        txt_wrong_answer = layout.findViewById(R.id.txt_wrong_answer) as TextView
        txt_wrong_answer.text = 0.toString()
        return true
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.question, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_done -> {
                if (!isAnswerModeView) {
                    MaterialStyledDialog.Builder(this@QuestionActivity)
                        .setTitle("Finish?")
                        .setDescription("Do you really want to finish?")
                        .setIcon(R.drawable.ic_mood_white_24dp)
                        .setNegativeText("No")
                        .onNegative { dialog, which -> dialog.dismiss() }
                        .setPositiveText("Yes")
                        .onPositive { dialog, which ->
                            finishGame()
                            drawer_layout.closeDrawer(Gravity.LEFT)
                        }.show()

                } else {
                    finishGame()
                }
            }
        }
        return true

    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        when (item.itemId) {
            R.id.nav_home -> {
                // Handle the camera action
            }
            R.id.nav_gallery -> {

            }
            R.id.nav_slideshow -> {

            }
            R.id.nav_tools -> {

            }
            R.id.nav_share -> {

            }
            R.id.nav_send -> {

            }
        }
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CODE_GET_RESULT)
        {
            if (resultCode == Activity.RESULT_OK)
            {
                val action = data!!.getStringExtra("action")
                if (action == null || TextUtils.isEmpty(action))
                {
                    val questionIndex = data.getIntExtra(Common.KEY_BACK_FROM_RESULT, -1)
                    view_pager.currentItem = questionIndex

                    isAnswerModeView = true
                    countDownTimer!!.cancel()

                    txt_wrong_answer.visibility = View.GONE
                    txt_right_answer.visibility = View.GONE
                    txt_timer.visibility = View.GONE
                }
                else
                {
                    if (action.equals("doquizagain"))
                        {
                            view_pager.currentItem = 0
                            isAnswerModeView = false

                        txt_wrong_answer.visibility = View.VISIBLE
                        txt_right_answer.visibility = View.VISIBLE
                        txt_timer.visibility = View.VISIBLE

                        for (i in Common.fragmentList.indices) {
                            Common.fragmentList[i].resetQuestion()
                        }

                        for (i in Common.answerSheetList.indices)
                            Common.answerSheetList[i].type = Common.ANSWER_TYPE.NO_ANSWER

                        adapter.notifyDataSetChanged()
                        questionHelperAdapter.notifyDataSetChanged()

                        countTimer()

                    } else if (action.equals("viewanswer"))
                    {
                        view_pager.currentItem = 0
                        isAnswerModeView = true
                        countDownTimer!!.cancel()

                        txt_wrong_answer.visibility = View.GONE
                        txt_right_answer.visibility = View.GONE
                        txt_timer.visibility = View.GONE

                        for (i in Common.fragmentList.indices)
                        {
                            Common.fragmentList[i].showCorrectAnswer()
                            Common.fragmentList[i].disableAnswer()
                        }
                        }
                    }
                }
            }
    }
}

My ResultActivity class:

package com.example.ecosense

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.widget.GridLayoutManager
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import com.example.ecosense.Adapter.ResultGridAdapter
import com.example.ecosense.Common.Common
import com.example.ecosense.Common.SpacesItemDecoration
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog
import kotlinx.android.synthetic.main.activity_question.*
import kotlinx.android.synthetic.main.activity_result.*
import kotlinx.android.synthetic.main.activity_result.txt_right_answer
import kotlinx.android.synthetic.main.content_question.*
import java.util.concurrent.TimeUnit

class ResultActivity : AppCompatActivity() {

    internal var backToQuestion:BroadcastReceiver = object:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent!!.action!!.toString() == Common.KEY_BACK_FROM_RESULT)
            {
                val questionIndex = intent.getIntExtra(Common.KEY_BACK_FROM_RESULT,-1)
                goBackActivityWithQuestionIndex(questionIndex)
            }
        }

    }

    private fun goBackActivityWithQuestionIndex(questionIndex: Int) {
        val returnIntent = Intent()
        returnIntent.putExtra(Common.KEY_BACK_FROM_RESULT,questionIndex)
        setResult(Activity.RESULT_OK,returnIntent)
        finish()

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_result,menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when(item!!.itemId)
        {
            R.id.menu_do_quiz_again -> doQuizAgain()
            R.id.menu_view_answer -> viewAnswer()
            android.R.id.home -> {
                val intent = Intent(applicationContext,CategoryActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                startActivity(intent) // Go back to category when click on back arrow in result activity
            }
        }
        return true
    }

    private fun viewAnswer() {
        val returnIntent = Intent()
        returnIntent.putExtra("action","viewanswer")
        setResult(Activity.RESULT_OK,returnIntent)
        finish()
    }

    private fun doQuizAgain() {

        MaterialStyledDialog.Builder(this@ResultActivity)
            .setTitle("Do quiz again?")
            .setDescription("Do you really want to delete this data?")
            .setIcon(R.drawable.ic_mood_white_24dp)
            .setNegativeText("No")
            .onNegative { dialog, which -> dialog.dismiss() }
            .setPositiveText("Yes")
            .onPositive { dialog, which ->

                val returnIntent = Intent()
                returnIntent.putExtra("action","doquizagain")
                setResult(Activity.RESULT_OK,returnIntent)
                finish()
            }
            .show()
    }

    override fun onDestroy() {
        LocalBroadcastManager.getInstance(this@ResultActivity)
            .unregisterReceiver(backToQuestion)
        super.onDestroy()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result)

        LocalBroadcastManager.getInstance(this@ResultActivity)
            .registerReceiver(backToQuestion, IntentFilter(Common.KEY_BACK_FROM_RESULT))

        toolbar.title = "Result"
        setSupportActionBar(toolbar)

        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        supportActionBar!!.setDisplayShowHomeEnabled(true)

        //
        txt_timer.text = (java.lang.String.format(
            "%02d:%02d",
            TimeUnit.MILLISECONDS.toMinutes(Common.timer.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(Common.timer.toLong()) - TimeUnit.MINUTES.toSeconds(
                TimeUnit.MILLISECONDS.toMinutes(
                    Common.timer.toLong()
                )
            )
        ))
        txt_right_answer.text = "${Common.right_answer_count}/${Common.questionList.size}"

        btn_filter_total.text = "${Common.questionList.size}"
        btn_filter_total.text = "${Common.right_answer_count}"
        btn_filter_total.text = "${Common.wrong_answer_count}"
        btn_filter_total.text = "${Common.no_answer_count}"

        val percent = Common.right_answer_count*100/Common.questionList.size
        if (percent > 80)
            txt_result.text = "Excellent!"
        else if (percent > 65)
            txt_result.text = "Good!"
        else if (percent > 50)
            txt_result.text = "Fair!"
        else
            txt_result.text = "Bad!"

        // Event Button
        btn_filter_total.setOnClickListener{
            val adapter = ResultGridAdapter(this,Common.answerSheetList)
            recycler_result.adapter = adapter
        }

        btn_filter_no_answer.setOnClickListener{
            Common.answerSheetListFiltered.clear()

            for (currentQuestion in Common.answerSheetList)
                if (currentQuestion.type == Common.ANSWER_TYPE.NO_ANSWER)
                    Common.answerSheetListFiltered.add(currentQuestion)
            val adapter = ResultGridAdapter(this,Common.answerSheetListFiltered)
            recycler_result.adapter = adapter
        }

        btn_filter_wrong.setOnClickListener{
            Common.answerSheetListFiltered.clear()

            for (currentQuestion in Common.answerSheetList)
                if (currentQuestion.type == Common.ANSWER_TYPE.WRONG_ANSWER)
                    Common.answerSheetListFiltered.add(currentQuestion)
            val adapter = ResultGridAdapter(this,Common.answerSheetListFiltered)
            recycler_result.adapter = adapter
        }

        btn_filter_right.setOnClickListener{
            Common.answerSheetListFiltered.clear()

            for (currentQuestion in Common.answerSheetList)
                if (currentQuestion.type == Common.ANSWER_TYPE.RIGHT_ANSWER)
                    Common.answerSheetListFiltered.add(currentQuestion)
            val adapter = ResultGridAdapter(this,Common.answerSheetListFiltered)
            recycler_result.adapter = adapter
        }

        // Set Adapter
        val adapter = ResultGridAdapter(this,Common.answerSheetList)
        recycler_result.setHasFixedSize(true)
        recycler_result.layoutManager = GridLayoutManager(this,4)
        recycler_result.addItemDecoration(SpacesItemDecoration(4))
        recycler_result.adapter = adapter

    }
}

Body:
So I found the error.. It was in the following code. I used txt_timer instead of txt_time, which resulted in a wrong layout reference...

        txt_timer.text = (java.lang.String.format(
            "%02d:%02d",
            TimeUnit.MILLISECONDS.toMinutes(Common.timer.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(Common.timer.toLong()) - TimeUnit.MINUTES.toSeconds(
                TimeUnit.MILLISECONDS.toMinutes(
                    Common.timer.toLong()
                )
            )
        ))

Correct code:

        txt_time.text = (java.lang.String.format(
            "%02d:%02d",
            TimeUnit.MILLISECONDS.toMinutes(Common.timer.toLong()),
            TimeUnit.MILLISECONDS.toSeconds(Common.timer.toLong()) - TimeUnit.MINUTES.toSeconds(
                TimeUnit.MILLISECONDS.toMinutes(
                    Common.timer.toLong()
                )
            )
        ))


来源: stackexchange

问:
Invoke rake task from Heroku Scheduler
How can I invoke a rake task from the Heroku scheduler?

I need to invoke the command rake sitemap:refresh (from an external library)

```<code># scheduler.rake

task :sitemap_refresh => :environment do
  Rails.application.eager_load!
  Rake::Task['-s sitemap:refresh'].invoke
end
</code>```

答: Use this as the command: bundle exec rake sitemap:refresh

ContentLicense: CC BY-SA 4.0

Title: Invoke rake task from Heroku Scheduler

Body:
How can I invoke a rake task from the Heroku scheduler?

I need to invoke the command rake sitemap:refresh (from an external library)

# scheduler.rake

task :sitemap_refresh => :environment do
  Rails.application.eager_load!
  Rake::Task['-s sitemap:refresh'].invoke
end


问:
C# foreach iterating rule for collections
How .NET decides for order of items when iterating through collections ?

For example:

```<code>list<string> myList = new List<string>();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // What's the order of items? a -> b -> c ?
}
</code>```

I need this order (accessing collection members):

```<code>for (int i = 1; i < myList.Count; i++)
{
    string item = myList[i - 1]; // This is the order I need
}
</code>```

Can I safely use foreach with List? What about other types of collections?

答:
I believe foreach starts at the first index and steps though until the last item in the list.

you can safely use foreach although I think it is a little slower than the for i=1; i < myList.count method.

Also, I would say you usually start at index 0. eg:

```<code>for (int i = 0; i < myList.Count -1 ; i++)
{
 string item = myList[i]; // This is the order I need
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How .NET decides for order of items when iterating through collections ?

For example:

list<string> myList = new List<string>();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // What's the order of items? a -> b -> c ?
}

I need this order (accessing collection members):

for (int i = 1; i < myList.Count; i++)
{
    string item = myList[i - 1]; // This is the order I need
}

Can I safely use foreach with List? What about other types of collections?

Body:
I believe foreach starts at the first index and steps though until the last item in the list.

you can safely use foreach although I think it is a little slower than the for i=1; i < myList.count method.

Also, I would say you usually start at index 0. eg:

for (int i = 0; i < myList.Count -1 ; i++)
{
 string item = myList[i]; // This is the order I need
}


问:
How to transfer a built Cython extension from a PC to another?
I have a PC in which I can not run setup.py file when I build a cython extension, because I do not have admin rights to install VC++ 14.0 (for python 3). So I decided to build the cython extension on another PC which works great. Now I want to transfer the cython module (for example helloword) to the other PC.

I tried to copied all the files generated after running setup.py, but it doesn't recognize the the modul with the following message:

I use python 3.7.3 to build the cython extension then copied all the files to python 3.6.1. Both PC are on windows. I use pycharm 2019 on both windows.

The structure of my project looks like below:

答:
As already mentionned in the commentaries, you cannot run a compiled cython for 3.7 in a 3.6 version (At least for windows). Also, the architecture should be exactly the same aswell (You cannot compile on a 32bits machine, and deploy it on a 64bits machine)

Once you solved all the dependency problem, you should run the python setup.py bdist_wheel command to create the wheel, and then run a pip install <path_to_wheel>


问:
Can't implement D3.js to React with useRef. What is the correct way?
I am trying to create a line chart with d3.js and implement it to React as a function component with hooks.

I tried to use useRef. Initialized them as null and then set them in the JSX as you can see in the code. When I want to use clientWidth which uses lineChart ref it says it is null.

I thought of creating an initializeDrawing function which will initialize empty assignments but then since component doesn't refresh at variable changes it doesn't work. I also thought of carrying those variables to useState but it doesn't seem like a good solution.

I want to learn from you what is the best solution to implement d3.js charts with function components.

I am trying to implement this example, but learning general principles of implementing d3.js to react function components with hooks is the main goal.

Here is the code:

```<code>...
...
...
const LineChart: FunctionComponent = (props) => {
  let dataArrIndex = 0;
  const lineChart = useRef((null as unknown) as HTMLDivElement);
  const xAxis = useRef((null as unknown) as SVGGElement);
  const yAxis = useRef((null as unknown) as SVGGElement);
  const margin = { top: 40, right: 40, bottom: 40, left: 40 };
  const aspectRatio = 9 / 16;
  const chartWidth = lineChart.current.clientWidth - margin.left - margin.right;
  const chartHeight =
    lineChart.current.clientWidth * aspectRatio - margin.top - margin.bottom;
  const yScale = d3.scaleLinear().range([chartHeight, 0]);
  const xScale = d3.scaleBand().range([0, chartWidth]);
  const update = () => {
    yScale.domain([
      0,
      d3.max(
        data,
        (d): number => {
          return d[dataArrIndex].balance;
        },
      ) as number,
    ]);

    xScale.domain(data[dataArrIndex].map((d) => d.month));

    d3.select(yAxis.current).call(d3.axisLeft(yScale));
    d3.select(xAxis.current).call(d3.axisBottom(xScale));
  };
  return (
    <div className="line-chart" ref={lineChart}>
      <svg width={chartWidth} height={chartHeight}>
        <g transform={`translate(${margin.left},${margin.bottom})`} />
        <g ref={yAxis} />
        <g ref={xAxis} />
        <path />
      </svg>
    </div>
  );
};

export default LineChart;

</code>```

答:
The problem is that you trying to use ref for element before this element created in dom, so you have null instead of ref to htmlelement. To solve your issue you need to wrap all code that uses refs to useEffect hook.

Something like this:

```<code>useEffect(() => {
  const chartWidth = lineChart.current.clientWidth - margin.left - margin.right;
  const chartHeight =
    lineChart.current.clientWidth * aspectRatio - margin.top - margin.bottom;
  const yScale = d3.scaleLinear().range([chartHeight, 0]);
  const xScale = d3.scaleBand().range([0, chartWidth]);
  const update = () => {
    yScale.domain([
      0,
      d3.max(
        data,
        (d): number => {
          return d[dataArrIndex].balance;
        },
      ) as number,
    ]);

    xScale.domain(data[dataArrIndex].map((d) => d.month));

    d3.select(yAxis.current).call(d3.axisLeft(yScale));
    d3.select(xAxis.current).call(d3.axisBottom(xScale));
  };
}
</code>```

Use effect uses in functional component as the analog for componentDidMount/componentDidUpdate/componentWillUnmount

And if you need to call method 'update' every time when component receive updates you need to move it from useEffect to function body and call it in ueEffect:

```<code>const update = () => {
    yScale.domain([
      0,
      d3.max(
        data,
        (d): number => {
          return d[dataArrIndex].balance;
        },
      ) as number,
    ]);

    xScale.domain(data[dataArrIndex].map((d) => d.month));

    d3.select(yAxis.current).call(d3.axisLeft(yScale));
    d3.select(xAxis.current).call(d3.axisBottom(xScale));
  };

useEffect(() => {
  const chartWidth = lineChart.current.clientWidth - margin.left - margin.right;
  const chartHeight =
    lineChart.current.clientWidth * aspectRatio - margin.top - margin.bottom;
  const yScale = d3.scaleLinear().range([chartHeight, 0]);
  const xScale = d3.scaleBand().range([0, chartWidth]);
  update();
}
</code>```

You can use attributes like width height in several ways:

Set it to state using useState hook: const { width, setWidth } = useState(0) and update it in useEffect from ref

Check if ref !== null <svg width={chartRef && chartRef.current.offsetWidth}  />

Body:
I am trying to create a line chart with d3.js and implement it to React as a function component with hooks.

I tried to use useRef. Initialized them as null and then set them in the JSX as you can see in the code. When I want to use clientWidth which uses lineChart ref it says it is null.

I thought of creating an initializeDrawing function which will initialize empty assignments but then since component doesn't refresh at variable changes it doesn't work. I also thought of carrying those variables to useState but it doesn't seem like a good solution.

I want to learn from you what is the best solution to implement d3.js charts with function components.

I am trying to implement this example, but learning general principles of implementing d3.js to react function components with hooks is the main goal.

Here is the code:

...
...
...
const LineChart: FunctionComponent = (props) => {
  let dataArrIndex = 0;
  const lineChart = useRef((null as unknown) as HTMLDivElement);
  const xAxis = useRef((null as unknown) as SVGGElement);
  const yAxis = useRef((null as unknown) as SVGGElement);
  const margin = { top: 40, right: 40, bottom: 40, left: 40 };
  const aspectRatio = 9 / 16;
  const chartWidth = lineChart.current.clientWidth - margin.left - margin.right;
  const chartHeight =
    lineChart.current.clientWidth * aspectRatio - margin.top - margin.bottom;
  const yScale = d3.scaleLinear().range([chartHeight, 0]);
  const xScale = d3.scaleBand().range([0, chartWidth]);
  const update = () => {
    yScale.domain([
      0,
      d3.max(
        data,
        (d): number => {
          return d[dataArrIndex].balance;
        },
      ) as number,
    ]);

    xScale.domain(data[dataArrIndex].map((d) => d.month));

    d3.select(yAxis.current).call(d3.axisLeft(yScale));
    d3.select(xAxis.current).call(d3.axisBottom(xScale));
  };
  return (

      <svg width={chartWidth} height={chartHeight}>
        <g transform={`translate(${margin.left},${margin.bottom})`} />
        <g ref={yAxis} />
        <g ref={xAxis} />
        <path />
      </svg>

  );
};

export default LineChart;

Body:
The problem is that you trying to use ref for element before this element created in dom, so you have null instead of ref to htmlelement. To solve your issue you need to wrap all code that uses refs to useEffect hook.

Something like this:

useEffect(() => {
  const chartWidth = lineChart.current.clientWidth - margin.left - margin.right;
  const chartHeight =
    lineChart.current.clientWidth * aspectRatio - margin.top - margin.bottom;
  const yScale = d3.scaleLinear().range([chartHeight, 0]);
  const xScale = d3.scaleBand().range([0, chartWidth]);
  const update = () => {
    yScale.domain([
      0,
      d3.max(
        data,
        (d): number => {
          return d[dataArrIndex].balance;
        },
      ) as number,
    ]);

    xScale.domain(data[dataArrIndex].map((d) => d.month));

    d3.select(yAxis.current).call(d3.axisLeft(yScale));
    d3.select(xAxis.current).call(d3.axisBottom(xScale));
  };
}

Use effect uses in functional component as the analog for componentDidMount/componentDidUpdate/componentWillUnmount

And if you need to call method 'update' every time when component receive updates you need to move it from useEffect to function body and call it in ueEffect:

const update = () => {
    yScale.domain([
      0,
      d3.max(
        data,
        (d): number => {
          return d[dataArrIndex].balance;
        },
      ) as number,
    ]);

    xScale.domain(data[dataArrIndex].map((d) => d.month));

    d3.select(yAxis.current).call(d3.axisLeft(yScale));
    d3.select(xAxis.current).call(d3.axisBottom(xScale));
  };

useEffect(() => {
  const chartWidth = lineChart.current.clientWidth - margin.left - margin.right;
  const chartHeight =
    lineChart.current.clientWidth * aspectRatio - margin.top - margin.bottom;
  const yScale = d3.scaleLinear().range([chartHeight, 0]);
  const xScale = d3.scaleBand().range([0, chartWidth]);
  update();
}

You can use attributes like width height in several ways:

Set it to state using useState hook: const { width, setWidth } = useState(0) and update it in useEffect from ref

Check if ref !== null <svg width={chartRef && chartRef.current.offsetWidth}  />


问:
Count the total (N) of duplicates in a column
I'm attempting to count the total number of duplicates in a column (not the individual duplicates).

```<code>from outputs
GROUP BY journal_id
HAVING ( COUNT(doi) > 1 )
WHERE journal_id = 1
</code>```

SQL TABLE

```<code>doi   journal_id
123       1
123       2
123       1
124       1

</code>```

The expected answer is 2

答:
The number of entire row duplicates can be calculated by taking the total number of rows and subtracting the number of distinct rows:

```<code>select a.cnt_all - d.cnt_individual
from (select count(*) as cnt_all
      from outputs
     ) a cross join
     (select count(*) as cnt_individual
      from (select distinct *
            from outputs
           ) d
     ) d;
</code>```

If you know your columns and your database supports multiple arguments to count(distinct), this can be radically simplified to:

```<code>select count(*) - count(distinct doi, journal_id)
from outputs;
</code>```

Or, if your database doesn't support this:

```<code>select sum(cnt - 1)
from (select doi, journal_id, count(*) as cnt
      from outputs
      group by doi, journal_id
     ) o;
</code>```

Body:
I'm attempting to count the total number of duplicates in a column (not the individual duplicates).

from outputs
GROUP BY journal_id
HAVING ( COUNT(doi) > 1 )
WHERE journal_id = 1

SQL TABLE

doi   journal_id
123       1
123       2
123       1
124       1

The expected answer is 2

Body:
The number of entire row duplicates can be calculated by taking the total number of rows and subtracting the number of distinct rows:

select a.cnt_all - d.cnt_individual
from (select count(*) as cnt_all
      from outputs
     ) a cross join
     (select count(*) as cnt_individual
      from (select distinct *
            from outputs
           ) d
     ) d;

If you know your columns and your database supports multiple arguments to count(distinct), this can be radically simplified to:

select count(*) - count(distinct doi, journal_id)
from outputs;

Or, if your database doesn't support this:

select sum(cnt - 1)
from (select doi, journal_id, count(*) as cnt
      from outputs
      group by doi, journal_id
     ) o;


问:
In vue, how do I check if any parent component has subscribed for an event which child is emitting?
I have a component which is sometimes being used as a child of a parent and sometimes it does not have any parent.

This component emits a particular event which either being caught by the parent ( if subscribed) or I would like to handle it by this component itself.

So at run time, How do I programmatically check

```<code>if (someone is listening to the event){
    let them catch and handle it
}else {
    let's handle it by our own
}
</code>```

答:
You can pass a boolean prop from your parent.

In Parent Component :

<Child :isParent='true'></Child>```
</div>
</div>
</p>

<p>In Child Component : </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>props : {
  isParent : Boolean
},

methods : {
  actionEvent : function(){
    if(this.isParent){
      // Emit event
    }
    else{
      // Take care over here.
    }
  }
}</code>```

Body:
I have a component which is sometimes being used as a child of a parent and sometimes it does not have any parent.

This component emits a particular event which either being caught by the parent ( if subscribed) or I would like to handle it by this component itself.

So at run time, How do I programmatically check

if (someone is listening to the event){
    let them catch and handle it
}else {
    let's handle it by our own
}

Body:
You can pass a boolean prop from your parent.

In Parent Component :

<Child :isParent='true'></Child>

In Child Component :

props : {
  isParent : Boolean
},

methods : {
  actionEvent : function(){
    if(this.isParent){
      // Emit event
    }
    else{
      // Take care over here.
    }
  }
}


问:
"Size or zero" of value of multivalued hashmap
I have a multivalued Hashmap (technically a LinkedHashMap):

```<code>private LinkedHashMap<String, ArrayList<BodyPart>> bodyParts  = new LinkedHashMap<>();
</code>```

I want to find the number of values associated with a given key.  However, bodyParts.get("sample key") returns null if the key isn't present, whereas I want it to return 0 (as there are zero values associated with that key).

I could shield it in an if statement:

```<code>int numberOfValues;
if(bodyParts.containsKey("sample"){
    numberOfValues = bodyParts.get("sample").size();
}
</code>```

but I was wondering if there is an easier/better way to do it?  I've read the documentation for computeIfPresent but, truthfully, didn't really understand it.

答:
Use Map.getOrDefault(Object key, V defaultValue).

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Body:
I have a multivalued Hashmap (technically a LinkedHashMap):

private LinkedHashMap<String, ArrayList<BodyPart>> bodyParts  = new LinkedHashMap<>();

I want to find the number of values associated with a given key.  However, bodyParts.get("sample key") returns null if the key isn't present, whereas I want it to return 0 (as there are zero values associated with that key).

I could shield it in an if statement:

int numberOfValues;
if(bodyParts.containsKey("sample"){
    numberOfValues = bodyParts.get("sample").size();
}

but I was wondering if there is an easier/better way to do it?  I've read the documentation for computeIfPresent but, truthfully, didn't really understand it.


问:
Materialized Key in SQLAlchemy
often when you have a table with selfrefernece, say in a tree, you have an attribute as a foreign key, which is pointing to the primary key of the table. (like in the Adjacency List Relationships example from the docs)

However, I have a natural key, which works like this:
"" is the root

"a", "b", "c" etc. are the children of ""

"aa", "ab", "ac" etc. are the children of "a"

"ba", "bb", "bc" etc. are the children of "b"

"aaa", "aab", "aac" etc. are the children of "aa"

So there is one character for each level in the tree and the child nodes of each node are those with the same beginning and one character added. This is called a "Materialized Key"

How would I do this using an SQLAlchemy mapper without adding an extra attribute to reference the parent?

Note: I'm only interested in reading the relationship, if something like node.children.append(child) isn't working thats fine. Also I'm stuck to version 0.4.8, however if this is not possible in this version but only in a newer one I might take the effort to update.

EDIT
I've gotten a first answer on the SA mailinglist. It works, but it's not mapper-based as I'd like it to be (e.g. to use eagerload)

答:
I do understand the constraint of the question, but why are you trying to avoid having an extra key? Sure, it is redundant information, but depending you your data (number of row, average length of the keys), having additional keys might actually improve your performance on SELECTs and you would be able to use eager-loading of the relationships in SA in the most trivial way.

For example, you could do the following:

Add another numeric identifier as PK and link the child/parent on this.

Add another string identifier to point to the parent object (Key: Varchar, ParentKey: Varchar). In some RDBMS (like MSSQL) you can have a PERSISTENT COMPUTED column, so that your client does not even have to provide the parent key and it will be calculated from the KEY column automatically using the formula (cut the last character). In this case you have have a DB Index on this column and very fast relationship retrievals.

Title: Materialized Key in SQLAlchemy


问:
how can I handle 2 actions on a button?
I was asking myself if with java fx's button it could be possible to handle 2 clicks. Like the 1st one is calling a function then the 2nd click will stop it. For example, I have a code where a button call a Marker over a lineChart but i want to disable it with the same button when I click on one time after I activate it.</p>

答:
As AmitD already said, you need to maintain some kind of persistence, like a globally scoped flag.
Then, when you press the button, check the flag, execute the desired function and toggle the flag.</p>

```<code>// in a scope higher than your action listener
boolean flag = false;

// code...

// action listener of your button:
if(flag){
    functionA();
} else {
    functionB();
}
flag = !flag;
</code>```

Title: how can I handle 2 actions on a button?

Body:
As AmitD already said, you need to maintain some kind of persistence, like a globally scoped flag.
Then, when you press the button, check the flag, execute the desired function and toggle the flag.

// in a scope higher than your action listener
boolean flag = false;

// code...

// action listener of your button:
if(flag){
    functionA();
} else {
    functionB();
}
flag = !flag;


问:
os.walk without digging into directories below
How do I limit os.walk to only return files in the directory I provide it?

```<code>def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        for f in files:
            if os.path.splitext(f)[1] in whitelist:
                outputList.append(os.path.join(root, f))
            else:
                self._email_to_("ignore")
    return outputList
</code>```

答:
Since Python 3.5 you can use os.scandir instead of os.listdir. Instead of strings you get an iterator of DirEntry objects in return. From the docs:

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because DirEntry objects expose this information if the operating system provides it when scanning a directory. All DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

You can access the name of the object via DirEntry.name which is then equivalent to the output of os.listdir

OwnerDisplayName: Setori

Body:
How do I limit os.walk to only return files in the directory I provide it?

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        for f in files:
            if os.path.splitext(f)[1] in whitelist:
                outputList.append(os.path.join(root, f))
            else:
                self._email_to_("ignore")
    return outputList