Reputation: 58
When i try to set size of my ImageView objet, i have always same error :
Attempt to write to field 'int android.view.ViewGroup$LayoutParams.width' on a null object reference
A piece of my code :
TableLayout tl = (TableLayout)findViewById(R.id.layoutDuNiveau);
for(int j=0;j<hauteurDuNiveau;j++){
TableRow tr = new TableRow(this);
tr.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
for(int i=0;i<largeurDuNiveau;i++){
imageViewDuNiveau[i][j] = new ImageView(this);
imageViewDuNiveau[i][j].setImageResource(R.drawable.blanc);
imageViewDuNiveau[i][j].requestLayout();
imageViewDuNiveau[i][j].getLayoutParams().width = 20; // ERROR HERE
imageViewDuNiveau[i][j].getLayoutParams().height = 20; // ERROR HERE
switch(tableauDuNiveau[i][j]){
case '#':
imageViewDuNiveau[i][j].setImageResource(R.drawable.mur);
default:
}
tr.addView(imageViewDuNiveau[i][j]);
}
tl.addView(tr);
}
Upvotes: 1
Views: 1800
Reputation: 132992
As see here:
This method may return null if this View is not attached to a parent ViewGroup or setLayoutParams(android.view.ViewGroup.LayoutParams) was not invoked successfully. When a View is attached to a parent ViewGroup, this method must not return null
To fix issue call add ImageView to tr
before accessing width
and height
:
tr.addView(imageViewDuNiveau[i][j]);
imageViewDuNiveau[i][j].getLayoutParams().width = 20;
imageViewDuNiveau[i][j].getLayoutParams().height = 20;
Upvotes: 4