Every time I go to add an Image view to my Linear Layout dynamically I get a null pointer exception.
LinearLayout tables = (LinearLayout) findViewById(R.id.table);
for(int i = 0; i < data.length; i++){
ImageView image = new ImageView(getApplicationContext());
try{
int imgID = getResources().getIdentifier(data[i], "drawable", "package");
image.setImageResource(imgID);
}catch(Exception e){
int imgID = getResources().getIdentifier("nia", "drawable", "package");
image.setImageResource(imgID);
}
tables.addView(image); //NULL POINTER THROWN HERE
}
When I debug, the imgID has a value, so I know its working. I just don’t understand why its null if
If this is the line that causes the Null Pointer Exception:
Then
tablesis null, simply findViewById() did not find any View with the idR.id.tablein the current layout being displayed.(If you want help figuring out why
tablesis null, please post the layout which you pass tosetContentView())Added from comments
Here is a general way to create a PopupWindow. This uses a LayoutInflator to inflate the layout so that we can access it to dynamically add elements to the layout. (Notice that we scope find to
popupLayout.findViewById(...)):Understand that the root element in
popup.xmlshould have abackgroundattribute defined otherwise the window is transparent by default.