Adding array of textviews dynamically to linear layout
android, layout, textview
Solution
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" />
Problem
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]); } ```