-2

I am building an Android application using Android Studio. I got an error of "Attempt to invoke virtual method 'int android.widget.SeekBar.getProgress()' on a null object reference". The application works well in the interface which i can see the progress and the "scale" text. However, when i need to submit this value to Firebase, the error mentioned occur.

In OnCreate method, I have defined the seekbar.

SeekBar seekBar = findViewById(R.id.seekBar);
    seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

I also had a onSeekBarChangeListener method.

SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
        scale.setText("How much do it related to you? (Max:5) : " + progress);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
};

I need to validate the values to make them update to firebase. The integer value of seekbar progress will be changed to String.

private void ValidateScale(){  

    String validProgress= String.valueOf(seekBar.getProgress());

    if(TextUtils.isEmpty(validProgress)){
        Toast.makeText(this, "Please insert the scale...", Toast.LENGTH_SHORT).show();
    }
    else{
        UpdateScale(validProgress);
    }}

I could not find out the problem of it become null as error stated as it shows the value on user interface. Please help me if anyone could found the problem. Thank you.

Mouris
  • 67
  • 1
  • 8
  • 3
    `seekBar` is null. You likely haven't used the correct ID, or it doesn't exist in the layout. – Doug Stevenson Mar 30 '20 at 21:14
  • 1
    if You use for example an `AlertDialog`, then the `seekbar` doesn*t exist in You activity, it exists in Your `alertDialog`. In such a case, You have to create a view and get the `seekbar` like `view.findViewByID()` – GGK stands for Ukraine Mar 30 '20 at 21:38
  • @DougStevenson ID is correct as the ID is seekBar in XML layout.. – Mouris Mar 31 '20 at 06:52
  • @GGK Thank you! I have added findViewByID() for seekBar in ValidateScale() method and it is working! – Mouris Mar 31 '20 at 07:01

1 Answers1

0

GGK's solution helped me to solve the problem! Thank you! The solution is define seekBar once again in ValidateScale() method.

private void ValidateScale(){  

  seekBar=findViewById(R.id.seekBar);
  String validProgress= String.valueOf(seekBar.getProgress());

  if(TextUtils.isEmpty(validProgress)){
      Toast.makeText(this, "Please insert the scale...", Toast.LENGTH_SHORT).show();
  }
   else{
    UpdateScale(validProgress);
  }}

And also thank you all for trying to help!

Mouris
  • 67
  • 1
  • 8