Vladimir
Vladimir

Reputation: 1243

Adding array of textviews dynamically to linear layout

I tried to add an array of textviews which i defined as a public variable, but when i run the application, it force closes as soon as it gets into for loop. This is the code:

LinearLayout myLayout = (LinearLayout) findViewById(R.id.my_layout);
            LayoutParams lp = new LayoutParams( LayoutParams.WRAP_CONTENT,    LayoutParams.WRAP_CONTENT);
            pairs=new TextView[num_match+1];
            for(int l=1;l<=num_match;l++)
            {
                pairs[l].setTextSize(15);
                pairs[l].setLayoutParams(lp);
                pairs[l].setId(l);
                pairs[l].setText(m1[l]+" - "+m2[l]);
                myLayout.addView(pairs[l]);
            }

Upvotes: 2

Views: 12263

Answers (3)

Sam
Sam

Reputation: 86948

You need to create new TextViews to put into the TextView array and you are skipping the first index (pairs[0]) which will lead to trouble later:

pairs=new TextView[num_match];
for(int l=0; l<num_match; l++)
{
    pairs[l] = new TextView(this);
    pairs[l].setTextSize(15);
    pairs[l].setLayoutParams(lp);
    pairs[l].setId(l);
    pairs[l].setText(m1[l + 1]+" - "+m2[l + 1]);
    myLayout.addView(pairs[l]);
}

From your comments, I included this simple working example to help you:

public class Example extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        LinearLayout myLayout = (LinearLayout) findViewById(R.id.my_layout);
        LayoutParams lp = new LayoutParams( LayoutParams.WRAP_CONTENT,    LayoutParams.WRAP_CONTENT);
        TextView[] pairs=new TextView[4];
        for(int l=0; l<4; l++)
        {
            pairs[l] = new TextView(this);
            pairs[l].setTextSize(15);
            pairs[l].setLayoutParams(lp);
            pairs[l].setId(l);
            pairs[l].setText((l + 1) + ": something");
            myLayout.addView(pairs[l]);
        }

    }
}

With the layout main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" />

Upvotes: 7

Shrikant Ballal
Shrikant Ballal

Reputation: 7087

Why have an array of TextViews? Can you replace it with ListView?

I think that would be a better way. Try this.

Upvotes: 0

LeeNeverGup
LeeNeverGup

Reputation: 1114

I think you need to initailize pairs[l] before using it, like this:

    for(int l=1;l<=num_match;l++)
    {
        pairs[l] = new TextView();
        //...
    }

Otherwise it will have NullPointerException, and collapse as described.

Upvotes: 3

Related Questions