Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy NullPointerException when programmatically add my text view?
    primarykey
    data
    text
    <p>I programmatically created a linear layout in my Activity like the following:</p> <pre><code>LinearLayout myContent = new LinearLayout(this); myContent.setOrientation(LinearLayout.VERTICAL); </code></pre> <p>Then, I defined a text view in xml (under res/layout/) like below:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;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" /&gt; </code></pre> <p>After that, I would like to add several <code>TextView</code> defined above to <code>myContent</code> linear layout programmatically like below:</p> <pre><code>//my content is a linear layout LinearLayout myContent = new LinearLayout(this); myContent.setOrientation(LinearLayout.VERTICAL); for(int i=0; i&lt;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(); </code></pre> <p>I thought the above code should add 10 <code>TextView</code> with name into <code>myContent</code> linear layout. But I end up with a <strong>NullPointerException</strong> at <code>nameField.setText(...);</code> (see above code) Why?</p> <h2>P.S. (Update)</h2> <p><code>myContent</code> Linear Layout is added to another linear layout which is defined in main.xml, and my activity <strong>has</strong> setContentView(R.layout.main)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload