0

I am trying to access to data class (Content)and I would like to use object(val isSelected: Boolean?)from PictureActivity. However, it causes UninitializedPropertyAccessException: lateinit property content has not been initialized. Do you know how to solve this situation? I used lateinit but I don't even know if using lateinit is the best way to access to data class(Content). If you know other way to access to it, please let me know.

The code is down below.

Content.kt

data class Content(
    val id: Int,
    val text: String,
    val isSelected: Boolean?,
    val url: String?
)

PictureActivity.kt

class PictureActivity : BaseActivity() {

    private lateinit var binding: PictureActivityBinding

    private lateinit var content: Content

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = PictureActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
     
        if(content.isSelected!!){
           binding.button1.setOnClickListner{
           startContentDownload(content.url!!)
             return@setOnClickListener
        }
     }
     private fun startContentDownload(url: String) {
        //download image
    }
  }
}
John
  • 17
  • 1
  • 8

2 Answers2

1

lateinit keyword in Kotlin gives you an option to initialize it later but make sure you do it before you use.

To check if that variable is initialized or not, you can use below:

if(::content.isInitialized) {
    // put your code here
}

In your case you have get data from somewhere(network call maybe) to fill in content data class, and then you will be able to use it.

Kapil Vij
  • 312
  • 2
  • 7
  • Thank you for the comment. It seems work for me! but when I click ```button1```, it does not detect click event.. – John Sep 16 '21 at 08:19
  • or do you know any other way to access to data class from activity without using lateini var? – John Sep 16 '21 at 08:29
0

You need to initialize the content variable first then only you can use it

content = Content(...)
Jack
  • 788
  • 3
  • 13
  • Thank you for the comment. Which line should I initialize? and How? – John Sep 16 '21 at 05:15
  • Just before accessing it in the `if` statement in `onCreate` `content = Content()` pass the parameters there because I don't know what values you will be using – Jack Sep 16 '21 at 05:18
  • If you don't have any value to start with better set the content to null for the first time – Jack Sep 16 '21 at 05:20
  • I see. There are more objects in data class ```Content``` but I did not add these to avoid confusion. What if I would like to use only two of them, not all of them from data class. – John Sep 16 '21 at 06:02
  • I added other objects ```id```and ```text``` on data class but I would like to use only ```isSelected```and ```url``` this time. – John Sep 16 '21 at 06:04
  • Making them nullable is the option right now – Jack Sep 16 '21 at 07:58