kavuru kavuru - 3 months ago 19
Android Question

NullPointerException while adding view in a fragment dynamically

I am trying to dynamically add a TableLayout into a LinearLayout inside a fragment.

Code below:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View rootview = inflater.inflate(R.layout.dashboard_fragment, container, false);
dash_board = (LinearLayout) rootview.findViewById(R.layout.dashboard_fragment);
table = new TableLayout(getActivity());
TableRow tr_header = new TableRow(getActivity());
TextView Name = new TextView(getActivity());

Name.setText("Name");
LayoutParams Name_params = new LayoutParams();
Name_params.width= 100;

Name.setLayoutParams(Name_params);
Name.setPadding(2, 0, 2, 2);

tr_header.addView(Name);

TextView Points = new TextView(getActivity());

Points.setText("Points");
LayoutParams point_params = new LayoutParams();
point_params.width= 100;

Points.setLayoutParams(point_params);
Points.setPadding(2, 0, 2, 2);

tr_header.addView(Points);

table.addView(tr_header);

dash_board.addView(table);

return rootview;
}


But while adding table to the dash board layout (dash_board.addView(table);) I am getting a
NullPointerException
.

What could the issue be?

Answer

Instead of this

View rootview = inflater.inflate(R.layout.dashboard_fragment, container, false);
    dash_board = (LinearLayout) rootview.findViewById(R.layout.dashboard_fragment);

it should be

LinearLayout dash_board = (LinearLayout)inflater.inflate(R.layout.dashboard_fragment,              container, false);
Comments