Home > Software design >  can anyone help me out why I am getting null value even there is no error in the code
can anyone help me out why I am getting null value even there is no error in the code

Time:07-24

package com.example.myquizapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ProgressBar
import android.widget.TextView

here is my code

class QuizActivity : AppCompatActivity() {
    private var progressBar : ProgressBar?= null
    private var tvProgress : TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) { 
            progressBar = findViewById(R.id.progressBar)  

on hover R.id.progressBar I get :public static final int progressBar = 1000004

            tvProgress = findViewById(R.id.tv_progress)

// public static final int tv_progress = 100000

//on hover progressBar I get : private final var progressBar: ProgressBar?

            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_quiz)

            var currentPosition = 1
            progressBar?.progress=currentPosition                       
            tvProgress?.text="${currentPosition}/${progressBar?.max}"
            Log.e("currentPosition" "${currentPosition})        // 1
            Log.e("ProgressBar", "${progressBar}")    // null, getting null value on logcat
            Log.e("TvOrogress", "${tvProgress}")// null, getting null value on logcat
            Log.e("tvProgress",${tvProgress?.text.toString}  // null

    }
}

CodePudding user response:

Move the findViewById() calls after setContentView().

setContentView() inflates the view hierarchy and adds it to the activity. findViewById() looks up view in the activity view hierarchy, and it is empty before setContentView() so findViewById() returns null.

CodePudding user response:

Move findViewById() to onViewCreated method

  override fun onViewCreated(savedInstanceState: Bundle?) { 
            progressBar = findViewById(R.id.progressBar) 
  • Related