How can I add NumberPicker on my Layout from Java code in my Android application?

166 views Asked by At

I am making a simple application. I want to add NumberPicker from my Java code, but when I run it, the applications closes immediately. Can someone tell me where is the error? I know that I can add it in XML, but I wanted to add it from Java code.

Thanks a lot

package com.example.openwebpage;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.NumberPicker;

public class MainActivity extends AppCompatActivity {
    NumberPicker np;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.layout);
        String[] displayed = {"1","2","3"};

        np = new NumberPicker(this);
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        np.setLayoutParams(layoutParams);

        np.setDisplayedValues(displayed);
        np.scrollBy(0,3);
        np.setMinValue(0);
        np.setMaxValue(3);

        np.setWrapSelectorWheel(true);

        layout.addView(np);


    }
}
1

There are 1 answers

0
Hamza Israr On BEST ANSWER

You need to update this code snippet:

np.scrollBy(0,2);
np.setMinValue(0);
np.setMaxValue(2);

The exception was Array Indexed Out of bound due to setMaxValue(3).