Null Pointer Exception when referencing main layout

余生颓废 提交于 2019-12-24 06:14:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!