0

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Also: remember: Class names must be mixed case, with the first letter of each inner word capitalized (CamelCase). In that case: 'QuestionActivity', 'UsernameStore'.
@Arnaldo: That is a popular convention. However, AFAIK, there are no capitalization rules for Kotlin classes.
1

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)

 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.