问题
I want this relative layout to eventually load an ad at the bottom.
public class Main extends Activity {
RelativeLayout mLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLayout = (RelativeLayout) findViewById(R.layout.main);
ImageView View = new ImageView(this, null); //example view
mLayout.addView(View);
Then the Null Pointer occurs below when mLayout is called
RelativeLayout.LayoutParams rparams = (LayoutParams) mLayout.getLayoutParams();
E/AndroidRuntime(4066): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.name.project/com.name.project.Main}: java.lang.NullPointerException
xml for the layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/lib/com.google.ads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
Any idea why this is happening here?
回答1:
The error occurs in this line:
mLayout = (RelativeLayout) findViewById(R.layout.main);
It's pretty obvious by the name of the findViewById
method - it's used to find a view by its ID, but you're trying to find a view using a layout reference, not ID reference. Try with the following:
mLayout = (RelativeLayout) findViewById(R.id.main);
Also, your RelativeLayout
should include the android:id
tag. Try using the following XML for your RelativeLayout
:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/lib/com.google.ads"
android:id="@+id/main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
来源:https://stackoverflow.com/questions/8735566/null-pointer-exception-when-referencing-main-layout