Tahlil
Tahlil

Reputation: 2731

Adding a button in linear layout crashes

I really do not understand why this simple code crashes in this line layout.addView(button);

super.onCreate(savedInstanceState);
    layout = (LinearLayout)findViewById(R.id.linearLayout);
    LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

    Button button = new Button(this);
    button.setHeight(100);
    button.setWidth(100);
    button.setText("HELLO");
    button.setLayoutParams(p);
    layout.addView(button);

activity_main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/linearLayout">
</LinearLayout>

EDIT: edited code still crushes. But now crushes in setContentView.

super.onCreate(savedInstanceState);

    layout = (LinearLayout)findViewById(R.id.linearLayout);
    setContentView(layout); 
    LayoutParams p = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);

    int i,j;
    Button button = new Button(this);
    button.setHeight(100);
    button.setWidth(100);
    button.setText("HELLO");
    layout.addView(button,p);

Logcat report enter image description here

Upvotes: 0

Views: 383

Answers (2)

Graeme
Graeme

Reputation: 25864

You're specifying the Views width height here:

button.setHeight(100);
button.setWidth(100);

then immediately overwriting it:

button.setLayoutParams(p);

try this, remove the setWidth and setLayoutParams and remove p:

  layout.addView(button, new LayoutParams(100,100));

Upvotes: 0

Egor
Egor

Reputation: 40203

Simply because you haven't called setContentView(). The root View of your Activity is null, so is layout.

Upvotes: 5

Related Questions