I am attempting to dynamically add FrameLayouts inside a RelativeLayout but am getting the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.addView(android.view.View)' on a null object reference
which occurs during rl.addView(fl)
public class StartingPage extends AppCompatActivity {
//set to 1 temporarily
int count = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_page);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.mainMenu);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100, Gravity.CENTER_HORIZONTAL| Gravity.CENTER_VERTICAL);
for(int i=0; i < count; i++){
FrameLayout fl = new FrameLayout(this);
fl.setLayoutParams(params);
TextView item = new TextView(this);
fl.addView(item);
rl.addView(fl);
}
}
}
My research seems to conclude that this would work, why is the FrameLayout fl null? I understand that a LayoutInflater is an option, which I have briefly tried to no avail, but it seems that many people were simply able to create the layouts and views and add them to the desired parent in this simpler manner.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:id="@+id/mainMenu"
tools:context="com.marcel.joseph.project.Main_Menu">
</RelativeLayout>
Furthermore, what makes a layout null? Is it the lack of children, undefined attributes, or something else?
Thanks