Why is there a NullPointerException when programmatically adding my text view?

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)

+4
source share
4 answers

If your R.id.name_text is in a different layout, you need to inflate this layout and then attach it.
because when you refer to R.id.name_text, it cannot be found, because your layout is missing if it is not inflated.

eg.

View child = getLayoutInflater (). inflate (R.layout.child);
myContent.addView (child);

+6
source

The problem is in this line.

  TextView nameField = (TextView)findViewById(R.id.name_text); 

There is a discrepancy with the spelling in the layout file. In addition, reassure setContentView(R.layout.main); I ran your code. It is working fine.

+2
source

You did not call setContentView (...) with the layout file. It looks like you might need to create 10 views in your code and apply a style instead.

You cannot access these 10 views with findViewById (...), since your layout file indicates only one view. You can also import this layout 10 times into the main layout file using LinearLayout, defined as the parent view.

0
source

Look at this Link check box. What you do is create the layout dynamically and with xml, just select it.

0
source

All Articles