findViewById returns null

Asked

Viewed 62 times

0

I am receiving null from my findViewById call, and I cannot understand why. The code below relates to a Activity in my program:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.dashboard);
        getLayoutInflater().inflate(R.layout.activity_cpc_select, frameLayout);

        TreeNode root = TreeNode.root();
        TreeNode parent = new TreeNode("MyParentNode");
        TreeNode child0 = new TreeNode("ChildNode0");
        TreeNode child1 = new TreeNode("ChildNode1");
        parent.addChildren(child0, child1);
        root.addChild(parent);

        AndroidTreeView tView = new AndroidTreeView(this, root);
        FrameLayout view= (FrameLayout) findViewById(R.id.cpc_tree_view);
        view.addView(tView.getView());    
    }

My layout is defined like this:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/cpc_tree_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>
</FrameLayout>
  • 1

    To use the method Activity#findViewById() must indicate that Activity uses the layout where that Framelayout is located through setContentView().

  • so it works. thank you!

1 answer

0


The problem is in the commented line of setContentView

Changing your code to:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);

        TreeNode root = TreeNode.root();
        TreeNode parent = new TreeNode("MyParentNode");
        TreeNode child0 = new TreeNode("ChildNode0");
        TreeNode child1 = new TreeNode("ChildNode1");
        parent.addChildren(child0, child1);
        root.addChild(parent);

        AndroidTreeView tView = new AndroidTreeView(this, root);
        FrameLayout view= (FrameLayout) findViewById(R.id.cpc_tree_view);
        view.addView(tView.getView());    
    }

you can access the view with findViewById(); Obligatorily, according to the documentation, every view that is initialized in an Activity has to be created with setContentView.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.