How to fix "Unresolved reference " error in Kotlin Android Studio 3.3
Asked Answered
M

4

10

I'm new to kotlin and Andriod studio. I was following a tutorial and everything was going smoothly until I received a ton of "Unresolved reference errors"

I looked at other peoples post concerning this problem but nothing seemed to help as I still receive multiple errors

I tried:

  • Build -> Clean -> Build -> Rebuild.
  • File -> Invalidate Caches and Restart
  • delete .idea/libraries -> File -> Sync Project with Gradle Files.

Here is my version information

Android Studio 3.3.1 Build #AI-182.5107.16.33.5264788, built on January 28, 2019 JRE: 1.8.0_152-release-1248-b01 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Windows 10 10.0

My code

package e.lakal.tapfighter

import android.content.ContentValues.TAG
import android.os.Bundle
import android.os.CountDownTimer
import android.os.PersistableBundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

internal lateinit var  tapmeButton: Button;
internal lateinit var GameScore: TextView;
internal lateinit var  Timer: TextView;
internal var  Score = 0
internal  var gameStarted = false

internal lateinit var countDownTimer : CountDownTimer
internal  val  initalCountDown: Long = 60000;
internal  val  CountDownInterval: Long = 1000;
internal val TAG = MainActivity::class.java.simpleName
internal val timeLeftonTimer : Long = 6000


companion object {
  private val SCORE_KEY ="SCORE_KEY"
  private val TIME_LEFT_KEY = "TIME_LEFT_KEY"
   }

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    Log.d(TAG, "On create called. Score is $Score")
    setSupportActionBar(toolbar)

    fab.setOnClickListener { view ->
        Snackbar.make(view, "Replace with your own action", 
      Snackbar.LENGTH_LONG)
            .setAction("Action", null).show()
    }

    tapmeButton = findViewById<Button>(R.id.tapmeButton)
    GameScore = findViewById<TextView>(R.id.GameScore)
    Timer = findViewById<TextView>(R.id.Timer)
    GameScore.text = getString(R.string.YourScore, Score.toString())

  tapmeButton.setOnClickListener{  view ->
      incrementScore()
   }
    resetGame()
     }




private fun resetGame(){

    Score = 0
    GameScore.text = getString(R.string.YourScore, Score.toString())
    val initalTimeLeft = initalCountDown / 1000
    Timer.text = getString(R.string.TimeLeft, 
      initalTimeLeft.toString())

    countDownTimer =  object: CountDownTimer(initalCountDown, 
     CountDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
           val  timeLeft = millisUntilFinished / 1000
            Timer.text = getString(R.string.TimeLeft, 
    timeLeft.toString())
        }

        override fun onFinish() {
         endGame()
        }
    }
 gameStarted =false;
}


  // Starts giving me problems here

}
 private fun startGame(){
    countDownTimer.start()
    gameStarted
 }


  override fun onSaveInstanceState(outState: Bundle?, 
  outPersistentState: PersistableBundle?) {
    super.onSaveInstanceState(outState, outPersistentState)

    outState?.putInt(SCORE_KEY, Score)
    outState?.putLong(TIME_LEFT_KEY, timeLeftonTimer)
    countDownTimer.cancel()

    Log.d(TAG,"onSaveInstanceState : Saving score : $Score & Saving 
 Time  current $timeLeftonTimer")

}
  override fun onDestroy(){
    super.onDestroy()
     Log.d(TAG, "onDestroy called.")
 }


private fun endGame(){
    Toast.makeText(this, getString(R.string.game_over_msg, Score.toString()), Toast.LENGTH_SHORT).show()
    resetGame()

}
private fun incrementScore() {
        if(!gameStarted){
            startGame() }
    Score++
    val newScore = getString(R.string.YourScore, Score.toString())
    GameScore.text = newScore
}



override fun onCreateOptionsMenu(menu: Menu): Boolean {

    menuInflater.inflate(R.menu.menu_main, menu)
    return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {

    return when (item.itemId) {
        R.id.action_settings -> true
        else -> super.onOptionsItemSelected(item)
    }
}
}

Logcat

019-02-24 17:49:13.359 2003-6170/? E/WakeLock: GCM_HB_ALARM release 
without a matched acquire!2019-02-24 17:49:13.450 1641-1769/? 
I/WifiService: getConnectionInfo uid=10013
2019-02-24 17:49:58.235 1641-1769/? D/WificondControl: Scan result 
 ready event
 2019-02-24 17:50:00.008 1641-1654/? E/memtrack: Couldn't load 
 memtrack module
 2019-02-24 17:50:00.008 1641-1654/? W/android.os.Debug: failed to 
 get memory consumption info: -1
 2019-02-24 17:50:00.016 1436-1454/? D/hwcomposer: hw_composer sent 
  6 syncs in 60s
 2019-02-24 17:50:00.111 1443-1443/? I/boot-pipe: done populating 
 /dev/random
 2019-02-24 17:50:15.532 1641-1658/? E/BatteryExternalStatsWorker: 
 modem info is invalid: ModemActivityInfo{ mTimestamp=0 
 mSleepTimeMs=0 mIdleTimeMs=0 mTxTimeMs[]=[0, 0, 0, 0, 0] 
  mRxTimeMs=0 mEnergyUsed=0}
Merow answered 24/2, 2019 at 23:3 Comment(2)
Hi, the logcat which you have posted has nothing to do with your app. Looks like you are getting build time error. can you post the build logs which you can find at the bottom next to logcat?Ellette
Any particular reason why your variables are internal?Inconspicuous
M
1

Managed to figure out the issue, apparently onSaveInstanceState() & onDestory() need to be moved under the onCreate function

Updated

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main_activity)
    Log.d(TAG, "On create called. Score is $Score")
    setSupportActionBar(toolbar)

    fab.setOnClickListener { view ->
        Snackbar.make(
            view, "Replace with your own action",
            Snackbar.LENGTH_LONG
        )
            .setAction("Action", null).show()
    }


    override fun onSaveInstanceState(
    outState: Bundle?,
    outPersistentState: PersistableBundle?
   ) {
     super.onSaveInstanceState(outState, outPersistentState)

    outState?.putInt(SCORE_KEY, Score)
    outState?.putLong(TIME_LEFT_KEY, timeLeftonTimer)
    countDownTimer.cancel()

    Log.d(ContentValues.TAG, "onSaveInstanceState : Saving score : $Score & Saving Time current $timeLeftonTimer")
}



override fun onDestroy() {
    super.onDestroy()
    Log.d(ContentValues.TAG, "onDestroy called.")
}
    
Merow answered 19/12, 2020 at 4:59 Comment(0)
T
1

Below of ' // Starts giving me problems here', the scope of methods is a root of a file, not inside of class.

So, I re-format your code and I can check 'Unresolved reference error' is disappeared exclude toolbar, fab, and R.**

Try it and notice to me result.

package e.lakal.tapfighter

import android.content.ContentValues
import android.content.ContentValues.TAG
import android.os.Bundle
import android.os.CountDownTimer
import android.os.PersistableBundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.appg.saltfactory.R
import com.google.android.material.snackbar.Snackbar

class MainActivity : AppCompatActivity() {

    internal lateinit var tapmeButton: Button;
    internal lateinit var GameScore: TextView;
    internal lateinit var Timer: TextView;
    internal var Score = 0
    internal var gameStarted = false

    internal lateinit var countDownTimer: CountDownTimer
    internal val initalCountDown: Long = 60000;
    internal val CountDownInterval: Long = 1000;
    internal val TAG = MainActivity::class.java.simpleName
    internal val timeLeftonTimer: Long = 6000


    companion object {
        private val SCORE_KEY = "SCORE_KEY"
        private val TIME_LEFT_KEY = "TIME_LEFT_KEY"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)
        Log.d(TAG, "On create called. Score is $Score")
        setSupportActionBar(toolbar)

        fab.setOnClickListener { view ->
            Snackbar.make(
                view, "Replace with your own action",
                Snackbar.LENGTH_LONG
            )
                .setAction("Action", null).show()
        }

        tapmeButton = findViewById<Button>(R.id.tapmeButton)
        GameScore = findViewById<TextView>(R.id.GameScore)
        Timer = findViewById<TextView>(R.id.Timer)
        GameScore.text = getString(R.string.YourScore, Score.toString())

        tapmeButton.setOnClickListener { view ->
            incrementScore()
        }
        resetGame()
    }


    private fun resetGame() {

        Score = 0
        GameScore.text = getString(R.string.YourScore, Score.toString())
        val initalTimeLeft = initalCountDown / 1000
        Timer.text = getString(
            R.string.TimeLeft,
            initalTimeLeft.toString()
        )

        countDownTimer = object : CountDownTimer(
            initalCountDown,
            CountDownInterval
        ) {
            override fun onTick(millisUntilFinished: Long) {
                val timeLeft = millisUntilFinished / 1000
                Timer.text = getString(
                    R.string.TimeLeft,
                    timeLeft.toString()
                )
            }

            override fun onFinish() {
                endGame()
            }
        }
        gameStarted = false;
    }


    // Starts giving me problems here
    private fun startGame() {
        countDownTimer.start()
        gameStarted
    }


    override fun onSaveInstanceState(
        outState: Bundle?,
        outPersistentState: PersistableBundle?
    ) {
        super.onSaveInstanceState(outState, outPersistentState)

        outState?.putInt(SCORE_KEY, Score)
        outState?.putLong(TIME_LEFT_KEY, timeLeftonTimer)
        countDownTimer.cancel()

        Log.d(
            ContentValues.TAG, "onSaveInstanceState : Saving score : $Score & Saving Time current $timeLeftonTimer")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(ContentValues.TAG, "onDestroy called.")
    }


    private fun endGame() {
        Toast.makeText(this, getString(R.string.game_over_msg, Score.toString()), Toast.LENGTH_SHORT).show()
        resetGame()

    }

    private fun incrementScore() {
        if (!gameStarted) {
            startGame()
        }
        Score++
        val newScore = getString(R.string.YourScore, Score.toString())
        GameScore.text = newScore
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {

        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }
}
Thilda answered 25/2, 2019 at 8:41 Comment(0)
M
1

Managed to figure out the issue, apparently onSaveInstanceState() & onDestory() need to be moved under the onCreate function

Updated

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main_activity)
    Log.d(TAG, "On create called. Score is $Score")
    setSupportActionBar(toolbar)

    fab.setOnClickListener { view ->
        Snackbar.make(
            view, "Replace with your own action",
            Snackbar.LENGTH_LONG
        )
            .setAction("Action", null).show()
    }


    override fun onSaveInstanceState(
    outState: Bundle?,
    outPersistentState: PersistableBundle?
   ) {
     super.onSaveInstanceState(outState, outPersistentState)

    outState?.putInt(SCORE_KEY, Score)
    outState?.putLong(TIME_LEFT_KEY, timeLeftonTimer)
    countDownTimer.cancel()

    Log.d(ContentValues.TAG, "onSaveInstanceState : Saving score : $Score & Saving Time current $timeLeftonTimer")
}



override fun onDestroy() {
    super.onDestroy()
    Log.d(ContentValues.TAG, "onDestroy called.")
}
    
Merow answered 19/12, 2020 at 4:59 Comment(0)
N
0

Try to change the gradle version from 3.3.1 to 3.2.1

classpath 'com.android.tools.build:gradle:3.2.1'
Norine answered 28/2, 2019 at 20:19 Comment(0)
M
0

I added id 'kotlin-android-extensions' in build.gradle(app) inside the plugin block like shown below and it solved my problem

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
}

for more details read this

Maiamaiah answered 30/5, 2022 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.