Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an array of views crashes an android app

Tags:

java

android

view

I have some part of an android app here which crashes for no apparent reason.

RL0 happens to be some LinearLayout defined in XML which already contains some other irrelevant stuff. To be honest with you, I've mostly worked with C++ so I might not initially know much about why some things are done significantly different in android, but I'm putting effort. Any help on how I can fix that crash? Error message states NullPointerException. Thanks.

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);
    }
}
like image 365
tgudelj Avatar asked Mar 25 '26 10:03

tgudelj


1 Answers

All elements in an Object array are null by default.

I.e. when you create the array:

page[] pages = new page[10];

you are only setting the size of the array but not setting 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 Java naming conventions show that class names start with an uppercase letter, for example

Page[] pages = new Page[10];
like image 59
Reimeus Avatar answered Mar 26 '26 22:03

Reimeus