Android: why is my linearlayout crashing when switching at runtime?-Collection of common programming errors
when user presses a button i would like to switch to the ‘details’ layout which is like this:
and this is how i am trying to switch it:
switch(item.getItemId())
{
case ID_DETAILS:
// show new layout to for details
LinearLayout detailsLayout = (LinearLayout) findViewById(R.id.layoutDetails);
LayoutInflater detailsvi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View detailsv = detailsvi.inflate(R.layout.activity_details, null);
// IT CRASHES ON THIS LINE
detailsLayout.addView(detailsv,new LinearLayout.LayoutParams(detailsLayout.getLayoutParams().width, detailsLayout.getLayoutParams().height));
return true;
}
It gives a null pointer exception error!!!
08-09 17:23:47.146: E/AndroidRuntime(1572): FATAL EXCEPTION: main
08-09 17:23:47.146: E/AndroidRuntime(1572): java.lang.NullPointerException
-
Here is how you solve this:
1) put a breakpoint on the crashline and run in debug mode. You can immediately see if detailsLayout is null or not. If not do step 2 Also check if detailsv is null.
2) details Object o1 = etailsLayout.getLayoutParams(); // check if this is null.
It has to be one or the other.
Update: Since its detailsLayout is in fact null. It must be that either
1) setContentView was not called prior to requsting detailsLayout, or 2) setContentView was set to a layout that did not define detailsLayout, or 3) setContentView was called correctly but detailsLayout is not correctly id in that layout file.
It must be one of these three.