Can't access variable in data class kotlin - android

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

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.

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

change text in android studio using viewBinding

I don't know why text is not changing in the BirthdayGreetingActivity.
No error is coming but it's not changing text. I checked(by Logcat) that name has came successfully to BirthdayGreetingActivity.kt from MainActivity.kt.
I guess that this [binding.birthdayGreeting.text = "Happy Birthday $name"] line in BirthdayGreetingActivity.kt is not working properly.
MainActivity.kt --
package com.example.firstapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.example.firstapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
fun createBirthdayCard(view: View){
val name = binding.nameInput.editableText.toString()
// Toast.makeText(this,"Name is $name",Toast.LENGTH_SHORT).show()
val intent = Intent(this,BirthdayGreetingActivity::class.java)
intent.putExtra(BirthdayGreetingActivity.NAME_EXTRA,name)
startActivity(intent)
}
}
BirthdayGreetingActivity.kt --
package com.example.firstapp
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.example.firstapp.databinding.ActivityBirthdayGreetingBinding
class BirthdayGreetingActivity : AppCompatActivity() {
private lateinit var binding: ActivityBirthdayGreetingBinding
companion object{
const val NAME_EXTRA ="name_extra"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBirthdayGreetingBinding.inflate(layoutInflater)
setContentView(R.layout.activity_birthday_greeting)
val name = intent.getStringExtra(NAME_EXTRA)
// val greet = binding.birthdayGreeting.editableText.toString()
// print(name)
// if (name != null) {
// Log.d("greet = ",binding.birthdayGreeting.editableText.toString())
// }
binding.birthdayGreeting.text = "Happy Birthday $name" [maybe something wrong here]
}
}
:) :) Thanks for spending your valuable time to help me :) :)
On BirthdayGreetingActivity you are passing the layout ID for setContentView, instead you must pass the binding.root, just like you did on MainActivity...
Change this line:
setContentView(R.layout.activity_birthday_greeting)
To:
setContentView(binding.root)

kotlin-android-extensions not working. what will be the problem?

I was following some guide(download android studio today) of kotlin and I have use the setText and it's not working.
what will be the problem?
package com.example.basic
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
Toast.makeText(applicationContext, "button was pressed.", Toast.LENGTH_LONG).show()
}
button2.setOnClickListener {
val input = editTextTextPersonName.text.toString()
TextView.setText("entered value: ${input}")
}
}
}
(I had tried replace setText to text but it's still red and can't save it)
Unresolved reference: setText(error)
TextView is the name of the class. You need to apply setText on an instance of the class. just like you did
editTextTextPersonName.text.toString()
instead of
EditText.text.toString()
I don't know that your TextView is called but you then need to do
instanceOfYourTextView.setText("entered value: ${input}")
As Mayur Gajra did mention you are not using the view from the XML but instead you are using the TextView class and this is your problem, what you need to have instead is something like this:
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
And then your MainActivity should look like the following:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
Toast.makeText(applicationContext, "button was pressed.", Toast.LENGTH_LONG).show()
}
button2.setOnClickListener {
val input = editTextTextPersonName.text.toString()
text.setText("entered value: ${input}")
}
}
}

I am not able to use viewbinding in activity in Kotlin android ,where I have also used companion object

package com.example.birthdayapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.example.birthdayapp.databinding.ActivityMainBinding
class birthdayActivity : AppCompatActivity() {
private lateinit var binding: birthdayActivity
//using companion object
companion object {
const val NAME_EXTRA="Name_extra"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//implementing view binding
binding= birthdayActivity.inflate(layoutInflater) //here red line shows below inflate
setContentView(binding.root) //here red line shows below root
//getting name from main activity
val name=intent.getStringExtra(NAME_EXTRA)
}
}
//MainActivity
package com.example.birthdayapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.birthdayapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityMainBinding.inflate(layoutInflater) //Here, I have successfully used viewbinding
setContentView(binding.root)
binding.birthdaybutn.setOnClickListener {
val name=binding.nam.editableText.toString()
val intent=Intent(this,birthdayActivity::class.java)
intent.putExtra(birthdayActivity.NAME_EXTRA,name)
startActivity(intent)
}
}
}
I have successfully used viewbinding in MainActivity but when I tried to use viewbindig in birthdayActivity , i got red lines for ( inflate and root keyword ) ,because i have used companion object in birthdayActiviy whereas I have not companion object in MainActiviy

Android Studio - Kotlin Project's "Unsolved reference" problem

I add a textView in layout but when I'm trying to use Kotlin Android Extensions but I get Unsolved reference error on my TextView:
package com.normal.ff
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
fun first(a:Int, b:Int){
textView.text
}
Add import kotlinx.android.synthetic.main.activity_main.* at the top of your activity.
You are almost there, you just need a reference from layout file for that text view.
something like below
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView = findViewById<TextView>(R.id.textView)
}
}
fun first (a:Int, b:Int){
val text = textView.text
}

How to properly implement an interface in android fragment?

folks. I have been working on a project with kotlin and I need to make a fragment that comunicate with the parent activity... I followed exactly what google and other websites suggested but I still get an error "activity does not override anything"... All of the other solutions are not working for me... here is the code .
FRAGMENT
package com.me.assistan.assistant
import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.LinearLayout
import android.widget.ToggleButton
import kotlinx.android.synthetic.main.content_newplan.*
import java.util.*
class addingTask : Fragment(), View.OnClickListener{
var func = Functions
var globalTask = GlobalTask
private lateinit var listener: OnTimeSettedListener
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnTimeSettedListener) {
listener = context
} else {
throw ClassCastException(context!!.toString() + " must implement
OnTimeSettedListener.")
}
}
companion object {
fun newInstance(): addingTask {
return addingTask()
}
}
override fun onCreateView(inflater: LayoutInflater?, container:
ViewGroup?,
savedInstanceState: Bundle?): View? {
val view: View = inflater!!.inflate(R.layout.fragment_adding_task,
container,
false)
val activity = activity
view.theTime.setOnClickListener { v ->
listener.onTimeSetListtedener("test")
}
return view
}
interface OnTimeSettedListener{
fun onTimeSetListtedener(comic : String){
println("ok")
}
}
}// Required empty public constructor
And not the MAIN ACTIVITY
class Newplan : AppCompatActivity(), addingTask.OnTimeSettedListener {
var posx = 0f
private var startx = 0f
private var posy = 0f
private var starty = 0f
var backIntent = Intent();
var func = Functions
var globalTask = GlobalTask
val fragment = addingTask()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_newplan)
if(savedInstanceState === null){
var args = Bundle()
supportFragmentManager.beginTransaction()
.add(R.id.taskMain, addingTask.newInstance(),"newTask")
.commit()
}
}
override fun onTimeSettedListener(comic : String){
println("params")
}
}
I get the error on the activity class... When I remove the "override?, the error is gone but nothing happen when I click on the button... What am I doing wrong?
I think you shouldn't add method body to your interface method. It is not allowed in Java. In Kotlin there is no error that showing method body is restricted. But you should remove body. Change your interface like
interface OnTimeSettedListener{
fun onTimeSetListtedener(comic : String)
}
Also actually you are not overriding your Listener's method. Method name in OnTimeSettedListener is onTimeSetListtedener but you are overriding onTimeSettedListener which is not really exist in your code.
Also as #albodelu mentioned answer and #chris mentioned in comments, you cannot write methods in methods. It is not correct usage.
As #chris commented, you need to move the lines below outside of onCreate() method:
override fun onTimeSettedListener(comic: String) {
println("params")
}
You also need to match names replacing
interface OnTimeSettedListener {
fun onTimeSetListtedener(comic : String){
println("ok")
}
}
by
interface OnTimeSettedListener {
fun onTimeSettedListener(comic: String) {
println("ok")
}
}
Update
If you fix the name typo and remove the default implementation of the onTimeSettedListener declaration in the interface inside your fragment, as your activity implements it and Android Studio warns you about the missing override, it's possible to click it and select that the IDE implements it for you to avoid errors doing it:
interface OnTimeSettedListener{
fun onTimeSettedListener(comic : String)
}
You also need to fix the call replacing:
listener.onTimeSetListtedener("test")
by
listener.onTimeSettedListener("test")

Categories

Resources