Home > Back-end >  Can't access variable in data class kotlin
Can't access variable in data class kotlin

Time:01-29

why can't I access a variable from another class? (the variable is in the data class, and when I want to access it, it throws "unresolved reference")

Here's what It looks like:

The code that tries to access the variable:


import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class questionActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_question)
        var nameDisplay: TextView = findViewById(R.id.nameDisplay)
        var name2 = usernameStore.username //here's the error, the "username" thing is red
        nameDisplay.setText(name2)

    }
}

The data Class:

package com.ketchup.myquizzies

public data class usernameStore (
   var username: String
)

Any help appreciated guys, I literally searched all things that came to my mind to solve this, but I couldn't help myself :(

Android Studio, Kotlin

CodePudding user response:

usernameStore is a class, not an object. You need to create an instance of usernameStore to be able to use it.

class questionActivity : AppCompatActivity() {
    val store = usernameStore()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_question)
        var nameDisplay: TextView = findViewById(R.id.nameDisplay)
        var name2 = store.username
        nameDisplay.setText(name2)

    }
}

FWIW, creating instances of classes is covered by this section of this chapter of this free book.

CodePudding user response:

You have not created instance of class

usernameStore

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class questionActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_question)
    var nameDisplay: TextView = findViewById(R.id.nameDisplay)
   // replace with below code
    var name2 = usernameStore().username
    nameDisplay.setText(name2)

 }
}
  • Related