I programmatically created a linear layout in my activity, for example:
LinearLayout myContent = new LinearLayout(this); myContent.setOrientation(LinearLayout.VERTICAL);
Then I defined the textual representation in xml (under res / layout /), as shown below:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/name_text" android:layout_width="80dp" android:layout_height="40dp" android:gravity="center" />
After that, I would like to add a few TextView defined above to myContent line layout programmatically, as shown below:
//my content is a linear layout LinearLayout myContent = new LinearLayout(this); myContent.setOrientation(LinearLayout.VERTICAL); for(int i=0; i<10; i++){ //get my text view resource TextView nameField = (TextView)findViewById(R.id.name_text); nameField.setText("name: "+Integer.toString(i)); //NullPointerException here } myContent.addView();
I thought the above code should add 10 TextView with a name in myContent line layout. But in the end I got a NullPointerException in nameField.setText(...); (see above code). Why?
PS (Update)
myContent Line layout is added to another linear layout, which is defined in main.xml, and my activity has setContentView (R.layout.main)
source share