Reputation: 379
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?
Upvotes: 0
Views: 171
Reputation: 104
Actually there is no dashboard_fragment as a ViewGroup in rootView because the rootView is exacly the dashboard_fragment as a ViewGroup.So these two lines of code are the cause of exception:
View rootview = inflater.inflate(R.layout.dashboard_fragment,container, false);
dash_board = (LinearLayout)rootview.findViewById(R.layout.dashboard_fragment);
Actually the logic will be correct if you do like this:
View rootview = inflater.inflate(R.layout.dashboard_fragment,container, false);
dash_board = (LinearLayout) rootView;
And this is the simplest form for this process:
dash_board =(LinearLayout)inflater.inflate(R.layout.dashboard_fragment,container, false);
Upvotes: 1
Reputation: 1289
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);
Upvotes: 0