Reputation: 41
I am building my first android app and I am trying to fill the screen with buttons that will be eventually populated from an SQLLite database. I can't figure out how to dynamically create a button.Right now my main activity has only a linear layout. When I try to dynamically create a button through the following code:
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainLayout);
Button addButton =new Button(this);
addButton.setText("add");
mainLayout.addView(addButton);
My app starts and then unexpectedly quits and LogCat throws these errors:
11-11 15:34:21.622: E/AndroidRuntime(16734): FATAL EXCEPTION: main
11-11 15:34:21.622: E/AndroidRuntime(16734): Process:
com.brycemacinnis.easycook, PID: 16734
11-11 15:34:21.622: E/AndroidRuntime(16734): java.lang.RuntimeException:
Unable to start activity ComponentInfo{com.brycemacinnis.easycook/com.brycemacinnis.easycook.MainActivity
}:java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.LinearLayout.addView(android.view.View)' on a null object reference
I've tried multiple ways I found online to create the buttons but each time the same thing happens. Is there anyway to fix this error? Eventually I would want the buttons to go into a scrollView.
Upvotes: 0
Views: 46
Reputation: 688
Your code for creating the buttons is correct
Button addButton = new Button(this);
The problem here is what this tells you:
android.widget.LinearLayout.addView(android.view.View)' on a null object reference
which comes from this line:
mainLayout.addView(addButton);
Why?
Because this line of code returns null:
findViewById(R.id.mainLayout);
Why does it return null?
Probably because you are either doing it too early (for example in onCreate in a Fragment) or you have provided the wrong layout id for your setContentView(R.layout.XXX) call (if you are in an activity).
Upvotes: 2