3

I want to create multiple TextViews inside a LinearLayout.The following code builds successfully but gives a NullPointerException at the line root.addView(t[i]);

public class MainActivity extends ActionBarActivity {
    TextView t[];
    LinearLayout root;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        root=(LinearLayout)findViewById(R.id.master);
        t=new TextView[10];
       LinearLayout.LayoutParams dim=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        for(int i=0;i<10;i++)
        {
            t[i]=new TextView(this);
            t[i].setLayoutParams(dim);
            t[i].setText("YOHOHO: "+i);
            root.addView(t[i]);
        }
        setContentView(root);
    }

This really has no aim Iam just trying to learn things!

0

2 Answers 2

4

It's giving NPE because you are not setting your activity layout properly.

Do this

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.whereLinearLayoutMasterIs); // Add your layout here
    root=(LinearLayout)findViewById(R.id.master);
    t=new TextView[10];
   LinearLayout.LayoutParams dim=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    for(int i=0;i<10;i++)
    {
        t[i]=new TextView(this);
        t[i].setLayoutParams(dim);
        t[i].setText("YOHOHO: "+i);
        root.addView(t[i]);
    }
}

NOTER.layout.whereLinearLayoutMasterIs is indicative, use your layout in which R.id.master is

Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that root is null - this is because you've not yet set your Activity's content view via setContentView. You need to do something like this:

super.onCreate(...); setContentView(R.layout.yourLayoutName); root=(LinearLayout)findViewById(R.id.master);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.