Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why NullPointerException when programmatically add my text view?

I programmatically created a linear layout in my Activity like the following:

LinearLayout myContent = new LinearLayout(this);
myContent.setOrientation(LinearLayout.VERTICAL);

Then, I defined a text view in xml (under res/layout/) like 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 several TextView defined above to myContent linear layout programmatically like 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 name into myContent linear layout. But I end up with a NullPointerException at nameField.setText(...); (see above code) Why?

P.S. (Update)

myContent Linear Layout is added to another linear layout which is defined in main.xml, and my activity has setContentView(R.layout.main)

like image 570
Mellon Avatar asked Feb 24 '23 12:02

Mellon


1 Answers

If your R.id.name_text is in another layout, you have to inflate that layout and then attach it,
because when you refer to R.id.name_text, it cannot be found because your layout is not present unless its inflated.

e.g.

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

like image 130
sat Avatar answered Mar 05 '23 16:03

sat