A
A
Artem2015-03-22 13:21:32
Android
Artem, 2015-03-22 13:21:32

NullPointerrException when calling addView(). How to fix?

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GameActivity">

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        android:id="@+id/container">


    </FrameLayout>
</RelativeLayout>

game activity:
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game);
        Field field = new Field(this);
    }

field:
public class Field extends View {
    private Context context;
    public Field(Context context) {
        super(context);
        this.context = context;
        createButton();
    }

    public void createButton()
    {
        FrameLayout container = (FrameLayout) findViewById(R.id.container);
        Button b = new Button(context);
        b.setText("123");
        b.setHeight(25);
        container.addView(b); //NullPointerrException
    }
}

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Abramov, 2015-03-22
@kivsiak

Everything is not so done.
1 - findViewById searches within the local layout and not at the ancestor. And the field has no layout at all.
2. The createButton code is generally heresy. The child view should not add itself to the container itself. As well as keep track of your sizes. The layout type is responsible for this.
developer.android.com/training/custom-views/index.html read this until you are enlightened.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question