Java – Adding a View array crashes the Android application

Adding a View array crashes the Android application… here is a solution to the problem.

Adding a View array crashes the Android application

I have here an Android app where some part crashes for no reason.

RL0 happens to be some LinearLayout defined in XML, which already contains some other unrelated things. To be honest, I mostly use C++, so I might not understand much at first why some things are so different in android, but I’m working on it. Any help on how to fix that crash?
The error message states NullPointerException.
Thank you.

public class Osteoporoza extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_osteoporoza);
        LinearLayout RL0=(LinearLayout)findViewById(R.id.RL0);        

page[] pages=new page[10];
        RL0.addView(pages[0].pageLL0);//doesn't crash without this line, yet i need to have some way of adding n objects that follow a pattern, i.e. a class.

class page
{
    public LinearLayout pageLL0;
        public ScrollView pageUpperScroll1;
            public TextView pageTextView2;
        public ScrollView pageLowerScroll1;
            public LinearLayout pageAnswerButtonLL2;
                public Button AnswerButton3_1;
                public Button AnswerButton3_2;
                public Button AnswerButton3_3;
                public Button AnswerButton3_4;

page()
    {
        pageAnswerButtonLL2.addView(AnswerButton3_1);
        pageAnswerButtonLL2.addView(AnswerButton3_2);
        pageAnswerButtonLL2.addView(AnswerButton3_3);
        pageAnswerButtonLL2.addView(AnswerButton3_4);

pageLowerScroll1.addView(pageAnswerButtonLL2);
        pageUpperScroll1.addView(pageTextView2);

pageLL0.addView(pageUpperScroll1);
        pageLL0.addView(pageLowerScroll1);
    }
}

Solution

By default, all elements in the Object array are null.

That is, when creating an array:

page[] pages = new page[10];

You only set the size of the array, not any instances within the array itself, so every element will be null. To instantiate each element you need to use:

for (int i=0; i < pages.length; i++) {
   pages[i] = new page();
}

Note that the Java naming convention indicates that class names begin with an uppercase letter, for example

Page[] pages = new Page[10];

Related Problems and Solutions